associateWithTo

inline suspend fun <K, V, M : MutableMap<in K, in V>> Flow<K>.associateWithTo(destination: M, crossinline valueSelector: suspend (K) -> V): M(source)

Collects this Flow into the given Map with the keys being the Flow elements and the corresponding values being obtained from them using valueSelector.

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("Jacob", "Bernoulli"))
val withLengthOfNames = mutableMapOf<Person, Int>()
println("withLengthOfNames.isEmpty() is ${withLengthOfNames.isEmpty()}") // true

scientists.associateWithTo(withLengthOfNames) { it.firstName.length + it.lastName.length }

println("withLengthOfNames.isNotEmpty() is ${withLengthOfNames.isNotEmpty()}") // true
// Jacob Bernoulli only occurs once in the map because only the last pair with the same key gets added
println(withLengthOfNames) // {Grace Hopper=11, Jacob Bernoulli=14}