Sort a Hashmap by Value in Java 8

Viewed 6106

I've got a HashMap that I need sorting by value and I'm trying to keep it concise, so I'm using Java 8. However various methods aren't working and I'm unsure why. I've tried this:

followLikeCount.values()
  .stream()
  .sorted(Map.Entry.comparingByValue())
  .collect(Collectors.toList());

Which throws this compile time exception:

Main.java:65: error: no suitable method found for sorted(Comparator<Entry<Object,V#1>>)
  .sorted(Map.Entry.comparingByValue())

I can't see why there is a mismatch from observation. I've also tried using the comparator:

Comparator<Map.Entry<Integer, Integer>> byValue =
          Map.Entry.<Integer, Integer>comparingByValue();

Which yields a similar error. Please could you advise why the comparators aren't valid?

1 Answers
Related