9.1.1.5 分组

原文链接: https://kotlinlang.org/docs/collection-grouping.html

9.1.1.5 分组

Kotlin 标准库提供了用于对集合元素分组的扩展函数。基本函数 groupBy() 接收一个 lambda 函数并返回一个 Map。在这个映射中,每个键是 lambda 的结果,对应的值则是返回该结果的那些元素组成的 List。例如,可以用这个函数按首字母对一组 String 分组。

你也可以给 groupBy() 传入第二个 lambda 实参——值转换函数。在带两个 lambda 的 groupBy() 返回的映射中,由 keySelector 函数产生的键会映射到值转换函数的结果,而不是原始元素。

这个例子演示了使用 groupBy() 函数按首字母对字符串分组,用 for 运算符遍历结果 Map 中的各个组,然后使用 valueTransform 函数把值转换为大写:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
fun main() {
    val numbers = listOf("one", "two", "three", "four", "five")

    // 使用 groupBy() 按首字母对字符串分组
    val groupedByFirstLetter = numbers.groupBy { it.first().uppercase() }
    println(groupedByFirstLetter)
    // {O=[one], T=[two, three], F=[four, five]}

    // 遍历每个组并打印键及其关联的值
    for ((key, value) in groupedByFirstLetter) {
        println("Key: $key, Values: $value")
    }
    // Key: O, Values: [one]
    // Key: T, Values: [two, three]
    // Key: F, Values: [four, five]

    // 按首字母对字符串分组并把值转换为大写
    val groupedAndTransformed = numbers.groupBy(keySelector = { it.first() }, valueTransform = { it.uppercase() })
    println(groupedAndTransformed)
    // {o=[ONE], t=[TWO, THREE], f=[FOUR, FIVE]}
}

如果你想先对元素分组,然后一次对所有组应用某个操作,请使用 groupingBy() 函数。它返回 Grouping 类型的实例。Grouping 实例让你以惰性方式对所有组应用操作:这些组实际上是在操作执行前才构建的。

具体来说,Grouping 支持以下操作:

  • eachCount() 统计每组中的元素个数。
  • fold() 和 reduce() 把每组当作单独的集合执行 fold 和 reduce 操作并返回结果。
  • aggregate() 依次对每组中的所有元素应用给定操作并返回结果。这是对 Grouping 执行任何操作的通用方式。当 fold 或 reduce 不够用时,可以用它来实现自定义操作。

你可以对 groupingBy() 函数生成的 Map 使用 for 运算符来遍历各个组。这样你就能访问每个键以及与该键关联的元素个数。

下面的例子演示如何使用 groupingBy() 函数按首字母对字符串分组、统计每组中的元素个数,然后遍历每个组打印键和元素个数:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
fun main() {
    val numbers = listOf("one", "two", "three", "four", "five")

    // 使用 groupingBy() 按首字母对字符串分组并统计每组的元素个数
    val grouped = numbers.groupingBy { it.first() }.eachCount()

    // 遍历每个组并打印键及其关联的值
    for ((key, count) in grouped) {
        println("Key: $key, Count: $count")
        // Key: o, Count: 1
        // Key: t, Count: 2
        // Key: f, Count: 2
    }
}