Pan*_* Ld 6 collections group-by kotlin
假设我的数据如下所示
data class Student(val name: String, val room: Int, val sex: String, val height: Int, val weight: Double){}
Run Code Online (Sandbox Code Playgroud)
我有一份学生名单
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))
Run Code Online (Sandbox Code Playgroud)
我的目标是将具有相同房间、性别和身高的学生分组,并对他们的体重求和
最终的列表应该是这样的
{
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>),
...
}
Run Code Online (Sandbox Code Playgroud)
(学生姓名可省略)
我已经看过Kotlin 中的 Nested groupBy但它没有回答我的问题。
当您需要按多个字段进行分组时,您可以使用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()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5906 次 |
最近记录: |