3

Is there a way to sort map entries by value where value is a collection? I want to sort entries by their collections' size. My code so far:

public Map<Object, Collection<Object>> sortByCollectionSize() {
    return myMap.entrySet().stream().sorted(Map.Entry.<Object, Collection<Object>>comparingByValue())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}
Naman
  • 27,789
  • 26
  • 218
  • 353
janlan
  • 477
  • 1
  • 5
  • 19

1 Answers1

3

You can get it working with Comparator.comparingInt as:

return myMap.entrySet()
            .stream()
            .sorted(Comparator.comparingInt(e -> e.getValue().size()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
Naman
  • 27,789
  • 26
  • 218
  • 353