groupByTo
inline suspend fun <T, K, M : MutableMap<in K, MutableList<T>>> Flow<T>.groupByTo(destination: M, crossinline keySelector: suspend (T) -> K): M(source)
Groups elements of the original Flow by the key returned by the given keySelector function applied to each element and puts each group key associated with the list of corresponding elements into the given Map.
Return
The destination map.
The operation is terminal.
val words = flowOf("a", "abc", "ab", "def", "abcd")
val byLength = words.groupBy { it.length }
println(byLength.keys) // [1, 3, 2, 4]
println(byLength.values) // [[a], [abc, def], [ab], [abcd]]
val mutableByLength: MutableMap<Int, MutableList<String>> = words.groupByTo(mutableMapOf()) { it.length }
// same content as in byLength map, but the map is mutable
println("mutableByLength == byLength is ${mutableByLength == byLength}") // trueContent copied to clipboard
inline suspend fun <T, K, V, M : MutableMap<in K, MutableList<V>>> Flow<T>.groupByTo(destination: M, crossinline keySelector: suspend (T) -> K, crossinline valueTransform: suspend (T) -> V): M(source)
Groups values returned by the valueTransform function applied to each element of the original Flow by the key returned by the given keySelector function applied to the element and puts each group key associated with the list of corresponding values into the given Map.
Return
The destination map.
The operation is terminal.
val nameToTeam = flowOf("Alice" to "Marketing", "Bob" to "Sales", "Carol" to "Marketing")
val namesByTeam = nameToTeam.groupByTo({ it.second }, { it.first })
println(namesByTeam) // {Marketing=[Alice, Carol], Sales=[Bob]}
val mutableNamesByTeam = nameToTeam.groupByTo(HashMap(), { it.second }, { it.first })
// same content as in namesByTeam map, but the map is mutable
println("mutableNamesByTeam == namesByTeam is ${mutableNamesByTeam == namesByTeam}") // trueContent copied to clipboard