associateBy

inline suspend fun <T, K> Flow<T>.associateBy(crossinline keySelector: suspend (T) -> K): Map<K, T>(source)

Collects this Flow into a Map with the keys provided by the keySelector function applied to each element.

If the same key is returned for more than one element by keySelector, the last one gets added to the map.

The entry iteration order of the resulting Map 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 = scientists.associateBy { it.lastName }

// 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}

inline suspend fun <T, K, V> Flow<T>.associateBy(crossinline keySelector: suspend (T) -> K, crossinline valueTransform: suspend (T) -> V): Map<K, V>(source)

Collects this Flow into a Map with the keys and values provided by the keySelector and valueTransform functions applied to each element.

If the same key is returned for more than one element by keySelector, the last one gets added to the map.

The entry iteration order of the resulting Map 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 = scientists.associateBy({ it.lastName }, { it.firstName })

// 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}