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。

相关方法

相关推荐
alexhilton2 小时前
深入理解withContext和launch的真正区别
android·kotlin·android jetpack
TDengine (老段)6 小时前
TDengine 转换函数 TO_JSON 用户手册
android·大数据·数据库·json·时序数据库·tdengine·涛思数据
q***42826 小时前
SpringCloudGateWay
android·前端·后端
卫生纸不够用6 小时前
Appium-锁屏-Android
android·appium
阿拉斯攀登6 小时前
安卓工控机 OTA 升级方案(SpringBoot+MQTT)
android·spring boot·物联网·iot
顾林海7 小时前
从0到1搭建Android网络框架:别再让你的请求在"路上迷路"了
android·面试·架构
花花鱼7 小时前
android room中实体类变化以后如何迁移
android
Jomurphys8 小时前
设计模式 - 适配器模式 Adapter Pattern
android
雨白8 小时前
电子书阅读器:解析 EPUB 底层原理与实战
android·html
g***B7388 小时前
Kotlin协程在Android中的使用
android·开发语言·kotlin