Calculate sum of all Map values in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<String, Integer> persons = new HashMap<>(); persons.put("John", 25); persons.put("Neil", 15); persons.put("Rosy", 18); int sum = persons.values().stream().mapToInt(Integer::intValue).sum(); System.out.println(sum); // 58 } } |
We can also perform a reduction operation on stream elements using the reduce() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<String, Integer> persons = new HashMap<>(); persons.put("John", 25); persons.put("Neil", 15); persons.put("Rosy", 18); int sum = persons.values().stream().reduce(0, Integer::sum); System.out.println(sum); // 58 } } |
2. Using for loop
Before Java 8, we can use replace the Stream API chain with a simple for loop:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<String, Integer> persons = new HashMap<>(); persons.put("John", 25); persons.put("Neil", 15); persons.put("Rosy", 18); int sum = 0; for (int value: persons.values()) { sum += value; } System.out.println(sum); // 58 } } |
That’s all about calculating the sum of all values in a Map<?, Integer> in Java.
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 :)