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.

Download Code

 
Another option is to perform a reduction operation on stream elements with the reduce() function.

Download Code

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:

Download Code

 
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.

Download Code

That’s all about calculating the sum of all values in a Kotlin Map.