Calculate sum of all values in a Kotlin Map
This article explores different ways to calculate the sum of all values in a Kotlin Map.
The idea is to get the collection of all values contained in the given map. This can be easily done with the values property, which retains the duplicate values in the map. Now the problem is reduced to finding the sum of all items in a collection. This can be achieved in several ways:
1. Using sum() function
The sum operation can be done trivially using the sum() function without any loops. It is available for all numeric data types. i.e, Int, Long, Float, Double, Byte, Short.
|
1 2 3 4 5 6 |
fun main() { val freq = mutableMapOf<String, Int>(Pair("A", 25), Pair("B", 15), Pair("C", 10)) val sum = freq.values.sum() println(sum) // 50 } |
Another option is to perform a reduction operation on stream elements with the reduce() function.
|
1 2 3 4 5 6 |
fun main() { val freq = mutableMapOf<String, Int>(Pair("A", 25), Pair("B", 15), Pair("C", 10)) val sum = freq.values.reduce { a, b -> a + b } println(sum) // 50 } |
2. Using Loop
The naive solution is to use a for-loop to calculate the sum of all elements in a list, as shown below:
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val freq = mutableMapOf<String, Int>(Pair("A", 25), Pair("B", 15), Pair("C", 10)) var sum = 0 for (value in freq.values) { sum += value } println(sum) // 50 } |
Alternatively, we can use the forEach() function to loop over each mapping in the map and accumulate the values’ sum in a counter of corresponding data type.
|
1 2 3 4 5 6 7 |
fun main() { val freq = mutableMapOf<String, Int>(Pair("A", 25), Pair("B", 15), Pair("C", 10)) var sum = 0 freq.values.forEach { sum += it } println(sum) // 50 } |
That’s all about calculating the sum of all values in a Kotlin Map.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)