associateTo
inline suspend fun <T, K, V, M : MutableMap<in K, in V>> Flow<T>.associateTo(destination: M, crossinline transform: suspend (T) -> Pair<K, V>): M(source)
Collects this Flow into the given Map with the key-value pairs provided by the transform function applied to each element.
The order in which key-value pairs get inserted into the destination is the order of the elements in the original Flow.
The operation is terminal.
data class Person(val firstName: String, val lastName: String)
val scientists = flowOf(Person("Grace", "Hopper"), Person("Jacob", "Bernoulli"), Person("Johann", "Bernoulli"))
val byLastName = mutableMapOf<String, String>()
println("byLastName.isEmpty() is ${byLastName.isEmpty()}") // true
scientists.associateTo(byLastName) { it.lastName to it.firstName }
println("byLastName.isNotEmpty() is ${byLastName.isNotEmpty()}") // true
// Jacob Bernoulli does not occur in the map because only the last pair with the same key gets added
println(byLastName) // {Hopper=Grace, Bernoulli=Johann}Content copied to clipboard