Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel operations on Kotlin collections?

In Scala, one can easily do a parallel map, forEach, etc, with:

collection.par.map(..) 

Is there an equivalent in Kotlin?

like image 971
HRJ Avatar asked Jan 09 '16 19:01

HRJ


People also ask

Are Kotlin coroutines parallel?

Kotlin's Coroutines enabling you to write parallel code easily, in a sequential way, and without worrying about the contextual overheads you know from using threads in Java.

What is concurrency in Kotlin?

When you extend your development experience from Android to Kotlin Multiplatform Mobile, you will encounter a different state and concurrency model for iOS. This is a Kotlin/Native model that compiles Kotlin code to native binaries that can run without a virtual machine, for example on iOS.

How do you use threads on Kotlin?

Creating a thread in Kotlin is similar to doing so in Java.class SimpleThread: Thread() { public override fun run() { println("${Thread. currentThread()} has run.") } } Or we can implement the Runnable interface: class SimpleRunnable: Runnable { public override fun run() { println("${Thread.


2 Answers

The Kotlin standard library has no support for parallel operations. However, since Kotlin uses the standard Java collection classes, you can use the Java 8 stream API to perform parallel operations on Kotlin collections as well.

e.g.

myCollection.parallelStream()         .map { ... }         .filter { ... } 
like image 153
yole Avatar answered Sep 21 '22 23:09

yole


As of Kotlin 1.1, parallel operations can also be expressed quite elegantly in terms of coroutines. Here is pmap on lists:

fun <A, B>List<A>.pmap(f: suspend (A) -> B): List<B> = runBlocking {     map { async(CommonPool) { f(it) } }.map { it.await() } } 

Note that coroutines are still an experimental feature.

like image 28
Alex Krauss Avatar answered Sep 21 '22 23:09

Alex Krauss