Kotlin groupingBy用法及代码示例

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

groupingBy 所在包 kotlin.text.groupingBy,其相关用法介绍如下:

用法:

kotlin 复制代码
inline fun <K> CharSequence.groupingBy(
    crossinline keySelector: (Char) -> K
): Grouping<Char, K>

从 char 序列创建一个 Grouping 源,以便稍后与 group-and-fold 操作之一一起使用,使用指定的 keySelector 函数从每个字符中提取一个键。

代码示例:

kotlin 复制代码
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}

相关方法

相关推荐
7ioik14 小时前
Explain关键字?
android
海盗123414 小时前
MySQL主从复制的配置方式
android·mysql·adb
liang_jy17 小时前
Android 事件分发机制(二)—— 点击事件透传
android·面试·源码
圆号本昊20 小时前
Flutter Android Live2D 2026 实战:模型加载 + 集成渲染 + 显示全流程 + 10 个核心坑( OpenGL )
android·flutter·live2d
冬奇Lab20 小时前
ANR实战分析:一次audioserver死锁引发的系统级故障排查
android·性能优化·debug
冬奇Lab21 小时前
Android车机卡顿案例剖析:从Binder耗尽到单例缺失的深度排查
android·性能优化·debug
ZHANG13HAO21 小时前
调用脚本实现 App 自动升级(无需无感、允许进程中断)
android
圆号本昊1 天前
【2025最新】Flutter 加载显示 Live2D 角色,实战与踩坑全链路分享
android·flutter
小曹要微笑1 天前
MySQL的TRIM函数
android·数据库·mysql