How to iterate and work with map key / values ​​using advanced Java 8 iterations

I read the answers, stating that I can do this effectively:

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

But none of the answers give an example for calculating something in a loop forEach. For example, if I have Map<String, Integer>, I would like to know how many values ​​let let say matter 5. How to do it in a loop forEach?

+4
source share
3 answers

I don’t know for what reason you want to calculate this in a loop forEach, since there are better one-line lines, 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]);
+2
source

forEach . values():

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

Collections frequency

Collections.frequency(map.values(), 5);
+2
source

Source: https://habr.com/ru/post/1688693/


All Articles