groupBy multiple fields in Kotlin and sum values

Viewed 3637

Assume that I have data looks like the following

data class Student(val name: String, val room: Int, val sex: String, val height: Int, val weight: Double){}

and I have a list of students

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))

My goal is to group the students with the same room, sex and height and sum their weight

The final list should be like this

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

(The students' name can be omitted)

I already looked at Nested groupBy in Kotlin but it did not answer my question.

1 Answers

When you need to group by several fields you can use Pair, Triple or your custom data class as a key for grouping

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