groupBy所在位置是kotlin.text.groupBy,其相關用法介紹如下。

用法一

inline fun <K> CharSequence.groupBy(
    keySelector: (Char) -> K
): Map<K, List<Char>>

通過應用於每個字符的給定keySelector 函數返回的鍵對原始字符序列的字符進行分組,並返回一個映射,其中每個組鍵與對應字符的列表相關聯。

返回的映射保留從原始字符序列生成的鍵的條目迭代順序。

例子:

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

用法二

inline fun <K, V> CharSequence.groupBy(
    keySelector: (Char) -> K, 
    valueTransform: (Char) -> V
): Map<K, List<V>>

通過應用於字符的給定 keySelector 函數返回的鍵對應用於原始字符序列的每個字符的 valueTransform 函數返回的值進行分組,並返回一個映射,其中每個組鍵與對應值的列表相關聯。

返回的映射保留從原始字符序列生成的鍵的條目迭代順序。

例子:

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