groupByTo所在位置是kotlin.sequences.groupByTo,其相关用法介绍如下。

用法一

inline fun <T, K, M : MutableMap<in K, MutableList<T>>> Sequence<T>.groupByTo(
    destination: M, 
    keySelector: (T) -> K
): M

通过应用于每个元素的给定keySelector 函数返回的键对原始序列的元素进行分组,并将与对应元素列表关联的每个组键放入destination 映射。

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val words = listOf("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}") // true
//sampleEnd
}

输出:

[1, 3, 2, 4]
[[a], [abc, def], [ab], [abcd]]
mutableByLength == byLength is true

返回

destination Map。

操作是 terminal

用法二

inline fun <T, K, V, M : MutableMap<in K, MutableList<V>>> Sequence<T>.groupByTo(
    destination: M, 
    keySelector: (T) -> K, 
    valueTransform: (T) -> V
): M

valueTransform函数返回的值分组到原始序列的每个元素,由给定的keySelector函数返回的键应用于元素并将每个组键映射到destination映射与对应值列表相关联的每个组键.

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val nameToTeam = listOf("Alice" to "Marketing", "Bob" to "Sales", "Carol" to "Marketing")
val namesByTeam = nameToTeam.groupBy({ 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}") // true
//sampleEnd
}

输出:

{Marketing=[Alice, Carol], Sales=[Bob]}
mutableNamesByTeam == namesByTeam is true

返回

destination Map。

操作是 terminal