Sobes.tech
Junior — Middle

Kuidas arvutada kõigi arvväärtuste summa kollektsioonis, millel on võtmed ja väärtused Kotlinis?

sobes.tech AI

Vastus AI-lt

In Kotlin, to calculate the sum of 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) // Will print 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) // Will print 30

Thus, to compute the sum of numeric values in a collection with keys and values, it is sufficient to obtain the values and apply the appropriate summing function.