Kotlin groupBy用法及代码示例

22 阅读1分钟

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

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

用法一

inline fun <T, K> Sequence<T>.groupBy(
    keySelector: (T) -> K
): Map<K, List<T>>

通过应用于每个元素的给定 keySelector 函数返回的键对原始序列的元素进行分组,并返回一个映射,其中每个组键与对应元素的列表相关联。

返回的映射保留从原始序列生成的键的条目迭代顺序。

操作是 terminal 。

代码示例:

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

用法二

inline fun <T, K, V> Sequence<T>.groupBy(
    keySelector: (T) -> K, 
    valueTransform: (T) -> V
): Map<K, List<V>>

通过应用于元素的给定keySelector 函数返回的键对应用于原始序列的每个元素的valueTransform 函数返回的值进行分组,并返回一个映射,其中每个组键与对应值的列表相关联。

返回的映射保留从原始序列生成的键的条目迭代顺序。

操作是 terminal 。

代码示例:

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

相关方法