Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do parallel flatMap in Kotlin?

I need to do parallel flat map. Let's say I have this code:

val coll: List<Set<Int>> = ...
coll.flatMap{set -> setOf(set, set + 1)}

I need something like this:

coll.pFlatMap{set -> setOf(set, set + 1)} // parallel execution
like image 319
Oleksandr.Bezhan Avatar asked Jun 03 '26 16:06

Oleksandr.Bezhan


1 Answers

Kotlin doesn’t provide any threading out of the box. But you can use kotlinx.coroutines to do something like this:

val coll: List<Set<Int>> = ...
val result = coll
 .map {set -> 
    // Run each task in own coroutine,
    // you can limit concurrency using custom coroutine dispatcher
    async { doSomethingWithSet(set) } 
 }
 .flatMap { deferred -> 
    // Await results and use flatMap
    deferred.await() // You can handle errors here
 }
like image 131
gildor Avatar answered Jun 06 '26 07:06

gildor