📜  hashmap values sum java(1)

📅  最后修改于: 2023-12-03 14:41:41.694000             🧑  作者: Mango

HashMap values sum in Java

Java HashMap is a widely used data structure that stores data in key-value pairs. Sometimes it's necessary to calculate the sum of all values in the HashMap. In this tutorial, we'll show you how to calculate the sum of all values in a HashMap in Java.

1. Using forEach() and values() method

The simplest way to calculate the sum of values in a HashMap is to use the forEach() method with the values() method. The forEach() method is used to loop through all the values in the HashMap, and the values() method returns a Collection view of the values contained in the HashMap.

HashMap<String, Integer> map = new HashMap<>();
// add some key-value pairs
int sum = 0;
for(Integer value : map.values()) {
    sum += value;
}

In the above example, we used a for-each loop with the values() method to iterate through all the values in the HashMap and add them to the sum variable.

2. Using Java 8 stream() API

Java 8 introduced the stream() API, which provides a concise way to perform bulk operations on collections of data. We can use the stream() API to convert the values of the HashMap into a Stream and then use the reduce() method to calculate the sum.

HashMap<String, Integer> map = new HashMap<>();
// add some key-value pairs
int sum = map.values().stream().mapToInt(Integer::intValue).sum();

In this example, we first convert the values of the HashMap into a stream using the stream() method. Then we use the mapToInt() method to convert the values into int elements and finally use the sum() method to calculate the sum of all the elements in the stream.

Conclusion

Calculating the sum of values in a HashMap is a common task in Java programming. In this tutorial, we've shown you two ways to calculate the sum of all values in a HashMap in Java. You can use whichever method that fits your use case best.