Stream : Summing Values in a Map

Stream : Summing Values in a Map

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.

Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
int totalScore = scores.values().stream()
.mapToInt(Integer::intValue)
.sum();

Binary Conversion in Java: A Comprehensive Guide

Leave a Reply

Your email address will not be published. Required fields are marked *