Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tasdemirbahadir/7897f5280a6efe4cbcec5ecbf4a168f9 to your computer and use it in GitHub Desktop.
Save tasdemirbahadir/7897f5280a6efe4cbcec5ecbf4a168f9 to your computer and use it in GitHub Desktop.
Java8 -> Convert list to a map where list contains duplicate keys
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