我需要做平行平面地图。假设我有这段代码:
val coll: List<Set<Int>> = ...
coll.flatMap{set -> setOf(set, set + 1)}
我需要这样的东西:
coll.pFlatMap{set -> setOf(set, set + 1)} // parallel execution
Kotlin不提供开箱即用的任何线程。但你可以使用kotlinx.coroutines做这样的事情:
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
}