Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the minimum score of each user from a list of maps using Java 8 stream

Assuming I have the following list of maps,

List<Map<String, Integer>> scores = new ArrayList<>();

scores.add(Collections.singletonMap("user1", 3));
scores.add(Collections.singletonMap("user3", 15));
scores.add(Collections.singletonMap("user1", 1));
scores.add(Collections.singletonMap("user2", 5));
scores.add(Collections.singletonMap("user2", 23));
scores.add(Collections.singletonMap("user1", 10));

I would like to extract the minumum score of each user into a map using Java 8 stream with lambda expressions. The desired result would be

{user1=1, user2=5, user3=15}

I tried this and it doesn't work,

Map<String, Integer> result = scores.stream()
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.minBy(Comparator.comparingInt(Map.Entry::getValue))));

Could anyone please tell me how to do it?

Thanks in advance.

like image 708
user5245796 Avatar asked Aug 20 '15 06:08

user5245796


1 Answers

Map<String, Integer> result = 
    scores.stream()
          .flatMap(map -> map.entrySet().stream())
          .collect(Collectors.toMap(Map.Entry::getKey,
                                    Map.Entry::getValue,
                                    Math::min));
like image 165
JB Nizet Avatar answered Jan 04 '23 15:01

JB Nizet