简体   繁体   中英

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

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?

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]);

另一种方法是使用Collections内置frequency方法

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM