'Group and calculate values in list
I have a list of classes (Kotlin)
class ChallengeRecord(
val sc: String,
val participant: String,
val hr: String,
val point: Int)
how can I group by participant and sum points by them?
I want to found kotlin analogue for java
Collectors.groupingBy() or Collectors.toMap()
Solution 1:[1]
.groupingBy { it.participant }
.fold(0){accumulator, element -> accumulator + element.point }
Solution 2:[2]
.groupBy { it.participant }
.mapValues { (_, challengeRecords) -> challengeRecords.sumOf { it.point } }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alexandr |
| Solution 2 | Alexandr |
