Stream : Summing Values in a Map
In this Java code snippet, a `Map` called `scores` is created to store name-score pairs. Two entries are added for “Alice” with a score of 90 and “Bob” with a score of 85.
The subsequent lines utilize Java 8 streams to extract the values (scores) from the `scores` map. These values are then mapped to integers using the `mapToInt` function, and finally, the `sum` function calculates the total score by adding up the individual scores.
1 2 3 4 5 6 | Map<String, Integer> scores = new HashMap<>(); scores.put( "Alice" , 90 ); scores.put( "Bob" , 85 ); int totalScore = scores.values().stream() .mapToInt(Integer::intValue) .sum(); |