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}