假设我有如下数据:
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,但它并没有回答我的问题。
fold(0) {...}
,因为如果只有 0 或 1 个元素,reduce 将会抛出异常。 - Animesh Sahu