Skip to content

Instantly share code, notes, and snippets.

@EricLondon
Created May 30, 2018 18:29
Show Gist options
  • Save EricLondon/5ca1472ab19f8f58f6de5b1e2fbe5c84 to your computer and use it in GitHub Desktop.
Save EricLondon/5ca1472ab19f8f58f6de5b1e2fbe5c84 to your computer and use it in GitHub Desktop.
Java 8 group Map by value, sort desc, and limit 10
Map<String, Long> counted = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map<String, Long> sorted = counted.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.limit(10)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment