Kotlin groupByTo用法及代码示例

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

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

用法一

kotlin 复制代码
inline fun <K, M : MutableMap<in K, MutableList<Char>>> CharSequence.groupByTo(
    destination: M, 
    keySelector: (Char) -> K
): M

通过应用于每个字符的给定keySelector 函数返回的键对原始字符序列的字符进行分组,并将与对应字符列表关联的每个组键放入destination 映射。

示例代码:

kotlin 复制代码
import kotlin.test.*

fun main(args: Array<String>) {
    //sampleStart
    val words = listOf("a", "abc", "ab", "def", "abcd")
    val byLength = words.groupBy { it.length }

    println(byLength.keys) // [1, 3, 2, 4]
    println(byLength.values) // [[a], [abc, def], [ab], [abcd]]

    val mutableByLength: MutableMap<Int, MutableList<String>> = words.groupByTo(mutableMapOf()) { it.length }
    // same content as in byLength map, but the map is mutable
    println("mutableByLength == byLength is ${mutableByLength == byLength}") // true
    //sampleEnd
}

// 输出
[1, 3, 2, 4]
[[a], [abc, def], [ab], [abcd]]
mutableByLength == byLength is true

返回destination Map。

用法二

kotlin 复制代码
inline fun <K, V, M : MutableMap<in K, MutableList<V>>> CharSequence.groupByTo(
    destination: M, 
    keySelector: (Char) -> K, 
    valueTransform: (Char) -> V
): M

由应用于原始字符序列的每个字符的valueTransform 函数返回的值由应用于字符的给定keySelector 函数返回的键分组,并将每个组键与对应的列表关联到destination 映射值。

示例代码:

kotlin 复制代码
import kotlin.test.*

fun main(args: Array<String>) {
    //sampleStart
    val nameToTeam = listOf("Alice" to "Marketing", "Bob" to "Sales", "Carol" to "Marketing")
    val namesByTeam = nameToTeam.groupBy({ it.second }, { it.first })
    println(namesByTeam) // {Marketing=[Alice, Carol], Sales=[Bob]}

    val mutableNamesByTeam = nameToTeam.groupByTo(HashMap(), { it.second }, { it.first })
    // same content as in namesByTeam map, but the map is mutable
    println("mutableNamesByTeam == namesByTeam is ${mutableNamesByTeam == namesByTeam}") // true
    //sampleEnd
}

// 输出
{Marketing=[Alice, Carol], Sales=[Bob]}
mutableNamesByTeam == namesByTeam is true

返回destination Map。

相关方法

相关推荐
JMchen1232 小时前
现代Android图像处理管道:从CameraX到OpenGL的60fps实时滤镜架构
android·图像处理·架构·kotlin·android studio·opengl·camerax
快点好好学习吧3 小时前
phpize 依赖 php-config 获取 PHP 信息的庖丁解牛
android·开发语言·php
是誰萆微了承諾3 小时前
php 对接deepseek
android·开发语言·php
Dxy12393102164 小时前
MySQL如何加唯一索引
android·数据库·mysql
冠希陈、6 小时前
PHP 判断是否是移动端,更新鸿蒙系统
android·开发语言·php
晚霞的不甘8 小时前
Flutter for OpenHarmony从零到一:构建《冰火人》双人合作闯关游戏
android·flutter·游戏·前端框架·全文检索·交互
2601_949833398 小时前
flutter_for_openharmony口腔护理app实战+饮食记录实现
android·javascript·flutter
独自破碎E9 小时前
【滑动窗口+字符计数数组】LCR_014_字符串的排列
android·java·开发语言
stevenzqzq9 小时前
compose 中 align和Arrangement的区别
android·compose
VincentWei959 小时前
Compose:MutableState 和 mutableStateOf
android