简体   繁体   中英

Stream an entrySet to groupingBy instead of keySet

I was watching a JavaOne video By Venkat Subramanian about lambdas .

He had an example like this:

Map<String, Integer>    scores  = new HashMap<>();
    scores.put("Jack", 12);
    scores.put("Jill", 15);
    scores.put("Tom", 11);
    scores.put("Darla", 15);
    scores.put("Nick", 15);
    scores.put("Nancy", 11);
    System.out.println(groupByScores(scores));

with this method:

public static Map<Integer, List<String>> groupByScores(Map<String, Integer> scores) {
    return scores.keySet().stream().collect(Collectors.groupingBy(scores::get));
}

The one thing that's a little bothersome about this is that it's essentially iterating over the keySet , calling map.get(key) for each key. But that's an antipattern in plain non-lambda code.

How can I get the same result, producing a "peopleByAge" map, but by iterating over the entrySet instead of the keySet ? The hard part is obviously everything past stream() .

return scores.entrySet().stream()
           .collect(Collectors.groupingBy(Map.Entry::getValue,
                    Collectors.mapping(Map.Entry::getKey,
                                       Collectors.toList())));

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