Junior — Middle
How to calculate the sum of all numeric values inside a collection with keys and values in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, to sum all numeric values within a collection with keys and values (for example, a Map), you can use the values function to get the collection of values, and then apply the sum() or sumOf function.
Example for Map<Int, Int>:
val map = mapOf("a" to 10, "b" to 20, "c" to 30)
val sum = map.values.sum()
println(sum) // Outputs 60
If the values are not just Ints, but, for example, objects with a numeric field, you can use sumOf:
data class Item(val count: Int)
val map = mapOf("a" to Item(10), "b" to Item(20))
val sum = map.values.sumOf { it.count }
println(sum) // Outputs 30
Thus, to sum numeric values in a collection with keys and values, it is enough to get the values and apply the appropriate summing function.