'Sum map values in kotlin
I have a map that structure like this:
"Alex": [Work(workPlace="workPlace", years=1),
Work(workPlace="workPlace", years=4),
Work(workPlace="workPlace", years=5),
Work(workPlace="workPlace", years=1)],
"John": [Work(workPlace="workPlace", years=2),
Work(workPlace="workPlace", years=2),
Work(workPlace="workPlace", years=1),
Work(workPlace="workPlace", years=6)]
What is the best way to sum the values?
For exampe, How can i sum all the years of Alex and John?
Solution 1:[1]
I think you're mostly looking for the mapValues
function, which allows you to transform a map's values, while keeping its keys. You could use this something like this:
val people: Map<String, List<Work>> = ...
val peopleToSumOfYears: Map<String, Int> =
people.mapValues { (name, works) -> works.sumOf { it.years } }
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 |