Created
July 5, 2018 06:18
-
-
Save tasdemirbahadir/7897f5280a6efe4cbcec5ecbf4a168f9 to your computer and use it in GitHub Desktop.
Java8 -> Convert list to a map where list contains duplicate keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
aList.stream() | |
.collect(Collectors.groupingBy(AnObject::getKeyField, toDescSortedList())) | |
.values() | |
.stream() | |
.map(list -> list.get(0)) | |
.collect(Collectors.toMap(AnObject::getKeyField, AnObject::getValueField)); | |
private static <AnObject> Collector<AnObject,?,List<AnObject>> toDescSortedList() { | |
return Collectors.collectingAndThen( | |
Collectors.toCollection(ArrayList::new), list -> { | |
list.sort(Comparator.comparing(AnObject::getUniqueField).reversed()); return list; | |
} ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment