kotlin - groupBy Kotlin 中的多个字段和求和值

标签 kotlin collections group-by

假设我的数据如下所示

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>),
...
}

(学生姓名可省略)

我已经看过 Nested groupBy in Kotlin但它没有回答我的问题。

最佳答案

当您需要按多个字段分组时,您可以使用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()

关于kotlin - groupBy Kotlin 中的多个字段和求和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62128593/

相关文章:

kotlin - 如何使用 Kotlin Dokka 记录主构造函数参数

java - 在 Java 中将字符串数组转换为 boolean 列表

Java 并发 - 队列效率高于列表

python - 如何找到数据框中的三个最大值?

c# - 使用按日期/月份分组的日期期间操作列表中的数据

kotlin - copyOfRange 中 Unresolved 引用错误

kotlin - 如何避免Kotlin中的重复覆盖字段

java - 在 Kotlin 中实例化对象时如何覆盖方法?

collections - 我如何通过其中一个字段索引一组记录?

python - 如何使用python统计员 worker 数来绘制散点图