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}

相关方法

相关推荐
ansondroider26 分钟前
Android 设置/修改系统NTP服务地址
android·时间同步·ntp
00后程序员张26 分钟前
Charles中文版抓包工具功能解析,提升API调试与网络性能优化
android·ios·小程序·https·uni-app·iphone·webview
2501_9160137412 小时前
iOS混淆工具有哪些?跨平台 App 混淆与保护的实用方案
android·ios·小程序·https·uni-app·iphone·webview
2501_9159090612 小时前
iOS 文件管理实战指南,用户文件、安全访问与开发调试方案
android·ios·小程序·https·uni-app·iphone·webview
没有了遇见15 小时前
Android虚拟机与虚拟空间检测实战详解<二>
android
峥嵘life16 小时前
Android初学者系统开发学习路线参考
android·学习
Kiri霧17 小时前
Kotlin反射
java·开发语言·kotlin
Xu_youyaxianshen18 小时前
Android 缓存日志(Logcat)导出与分析全攻略
android·缓存·log日志
黑白小道士18 小时前
Kotlin 中,run、also、let、apply、with 是常用的作用域函数
android·kotlin
0wioiw020 小时前
Android-Kotlin基础(Jetpack③-LiveData)
android·开发语言·kotlin