Skip to content

Instantly share code, notes, and snippets.

@ToxicBakery
Last active February 21, 2017 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ToxicBakery/8238fcc91d154fcfed3fc1980467fe71 to your computer and use it in GitHub Desktop.
Save ToxicBakery/8238fcc91d154fcfed3fc1980467fe71 to your computer and use it in GitHub Desktop.
Kotlin parallel map extension function.
/**
 * Operate on a stream of inputs in parallel returning the list of results.
 *
 * @see <a href="http://stackoverflow.com/a/35638609/1286667">Parallel operations on Kotlin collections?</a>
 */
fun <T, R> Iterable<T>.parallelMap(
        numThreads: Int = Runtime.getRuntime().availableProcessors(),
        exec: ExecutorService = Executors.newFixedThreadPool(numThreads),
        transform: (T) -> R): List<R> {

    return this.map { exec.submit(Callable { transform(it) }) }
            .toList()
            .map(Future<R>::get)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment