Sum map values in kotlin

Viewed 3345

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?

2 Answers

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 } }
val sum = map.values.sum()

This should work faster with approx. O(N) complexity because values are already stored in a list. And mapValues with sumOf is about O(2N) because of 2 loops inside.

Related