associateByTo
inline suspend fun <T, K, M : MutableMap<in K, in T>> Flow<T>.associateByTo(destination: M, crossinline keySelector: suspend (T) -> K): M(source)
Collects this Flow into the given Map with the keys provided by the keySelector 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) {
override fun toString(): String = "$firstName $lastName"
}
val scientists = flowOf(Person("Grace", "Hopper"), Person("Jacob", "Bernoulli"), Person("Johann", "Bernoulli"))
val byLastName = mutableMapOf<String, Person>()
println("byLastName.isEmpty() is ${byLastName.isEmpty()}") // true
scientists.associateByTo(byLastName) { it.lastName }
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 Hopper, Bernoulli=Johann Bernoulli}Content copied to clipboard
inline suspend fun <T, K, V, M : MutableMap<in K, in V>> Flow<T>.associateByTo(destination: M, crossinline keySelector: suspend (T) -> K, crossinline valueTransform: suspend (T) -> V): M(source)
Collects this Flow into the given Map with the keys and values provided by the keySelector and valueTransform functions 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.associateByTo(byLastName, { it.lastName }, { 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