This post will discuss how to calculate the sum of all values in a Map<?, Integer> in Java.

We can easily get a collection view of the values contained in this map using the values() method. Now the task is reduced to summing up all values in a collection. This can be done in several ways in Java:

1. Using Java 8

In Java 8 or above, the sum operation can be done trivially using Streams without any loops.

Download  Run Code

 
We can also perform a reduction operation on stream elements using the reduce() method.

Download  Run Code

2. Using for loop

Before Java 8, we can use replace the Stream API chain with a simple for loop:

Download  Run Code

That’s all about calculating the sum of all values in a Map<?, Integer> in Java.