How to iterate and work on Map key/values using improved Java 8 iterations

Viewed 105

I have read answers stating I can effectively do this:

map.forEach((key, value) -> {
    System.out.println("Key : " + key + " Value : " + value);
});

But none of the answers provide example on computing something within the forEach loop. For instance, if I have a Map<String, Integer>, I would like to find how many values have a value of let's say 5. How do I do this inside the forEach loop?

3 Answers

I wouldn't use forEach for this. Instead, I'd stream the map's values():

long fives = map.values().stream().filter(v -> v == 5L).count();

I don't know for what reason you want to compute this in the forEach loop, as there are nicer one-liners as others have already pointed out, but you can do it like this:

final int[] count = {0};
map.forEach((key, value) -> {
    if (value == 5)
        count[0]++;
});
System.out.println(count[0]);

Another way to do this shall be using the Collections built-in frequency method as

Collections.frequency(map.values(), 5);
Related