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}

相关方法

相关推荐
Meteors.20 小时前
安卓进阶——RxJava
android·rxjava
drsonxu1 天前
Android开发自学笔记 --- 构建简单的UI视图
android·compose
onthewaying1 天前
在Android平台上使用Three.js优雅的加载3D模型
android·前端·three.js
带电的小王1 天前
Android设备:无busybox工具解决
android·busybox
默契之行1 天前
为什么要使用 .asStateFlow() 而不是直接赋值?
kotlin
一 乐1 天前
个人健康系统|健康管理|基于java+Android+微信小程序的个人健康系统设计与实现(源码+数据库+文档)
android·java·数据库·vue.js·spring boot·生活
百锦再1 天前
第14章 智能指针
android·java·开发语言·git·rust·go·错误
陈老师还在写代码1 天前
android studio 里的 activity 和 layout 是怎么关联上的
android·ide·android studio
河铃旅鹿1 天前
Android开发-java版:BroadcastReceiver广播
android·笔记·学习
程序员老刘1 天前
华为小米都在布局的多屏协同,其实Android早就有了!只是你不知道...
android·flutter