Kotlin中按多个字段分组并求和值

6
假设我有如下数据:
data class Student(val name: String, val room: Int, val sex: String, val height: Int, val weight: Double){}

我有一个学生名单

val students = listOf(
     Student("Max", 1, "M", 165, 56.8),
     Student("Mint", 1, "F", 155, 53.2),
     Student("Moss", 1, "M", 165, 67.3),
     Student("Michael", 2, "M", 168, 65.6),
     Student("Minnie", 2, "F", 155, 48.9),
     Student("Mickey", 1, "M", 165, 54.1),
     Student("Mind", 2, "F", 155, 51.2),
     Student("May", 1, "F", 155, 53.6))

我的目标是根据房间、性别和身高将学生分组,并累加他们的体重。

最终列表应该如下所示:

{
Student(_, 1, "M", 165, <sum of weight of male students who is in 1st room with height 165>),
Student(_, 1, "F", 155, <sum of weight of female students who is in 1st room with height 155>),
...
}

可以省略学生的名字。

我已经查看了Kotlin中的嵌套 groupBy,但它并没有回答我的问题。

1个回答

7

当您需要根据多个字段进行分组时,可以使用PairTriple或自定义数据类作为分组的键。

val result = students
    .groupingBy { Triple(it.room, it.sex, it.height) }
    .reduce { _, acc, element ->
        acc.copy(name = "_", weight = acc.weight + element.weight)
    }
    .values.toList()

请使用 fold(0) {...},因为如果只有 0 或 1 个元素,reduce 将会抛出异常。 - Animesh Sahu
OwO,Kotlin 的文档有些令人困惑,它们说会抛出异常。请参阅 https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/reduce.html。 - Animesh Sahu
@AnimeshSahu 对于常规数组和列表,这是可行的,但对于分组减少不适用。 - IR42
@AnimeshSahu 我尝试了0和1个元素,它没有抛出任何异常。 - Pandarian Ld
True,reduce仅适用于数组和列表 https://pl.kotl.in/w3MW7hm5n 上面的IR42代码是安全的 :) - Animesh Sahu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接