假设我的数据如下所示
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但它没有回答我的问题。
最佳答案
当您需要按多个字段分组时,您可以使用Pair
、Triple
或您的自定义数据类作为分组键
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/