Kotlin groupingBy用法及代码示例

49 阅读1分钟

本文方法及代码示例基于 Kotlin 2.1.20 Released

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}

相关方法