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.
Map<String, Integer> result =
scores.stream()
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
Math::min));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With