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

用法:

inline fun <K> CharSequence.groupingBy(
    crossinline keySelector: (Char) -> K
): Grouping<Char, K>

從 char 序列創建一個 Grouping 源,以便稍後與 group-and-fold 操作之一一起使用,使用指定的 keySelector 函數從每個字符中提取一個鍵。

例子:



fun main(args: Array<String>) {
//sampleStart
val words = "one two three four five six seven eight nine ten".split(' ')
val frequenciesByFirstChar = words.groupingBy { it.first() }.eachCount()
println("Counting first letters:")
println(frequenciesByFirstChar) // {o=1, t=3, f=2, s=2, e=1, n=1}

val moreWords = "eleven twelve".split(' ')
val moreFrequencies = moreWords.groupingBy { it.first() }.eachCountTo(frequenciesByFirstChar.toMutableMap())
println(moreFrequencies) // {o=1, t=4, f=2, s=2, e=2, n=1}
//sampleEnd
}

輸出:

Counting first letters:
{o=1, t=3, f=2, s=2, e=1, n=1}
{o=1, t=4, f=2, s=2, e=2, n=1}