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}

相关方法

相关推荐
mmsx6 小时前
Android 新闻资讯客户端实战:从零搭建一个完整的新闻 App
android·app·源码
三8447 小时前
PHP 绕过污点追踪构造 Webshell:反序列化引用复用与 Trait 可变函数 RCE
android
石头猫灯7 小时前
WordPress wp2shell漏洞断点逐过程到注入点
android·学习
Android打工仔8 小时前
Kotlin 协程源码解析(五):BaseContinuationImpl.resumeWith() —— Continuation 链是如何被展开的?
android·kotlin
存在morning9 小时前
【PySpark 学习笔记 三】DataFrame API 入门
android·java·数据库
YSoup9 小时前
2026 安卓面试助手APP(安卓八股、题库)
android·面试·职场和发展
xcyxiner9 小时前
flutter 运行到模拟器上
android·前端·flutter
Android-Flutter9 小时前
android Glide 源码流程分析
android·kotlin
Android-Flutter10 小时前
android Glide 使用详解
android·kotlin
恋猫de小郭10 小时前
Dart 3.13 的到底改了什么?为什么很重要?有什么坑?
android·前端·flutter