4

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?

Bryn
  • 53
  • 1
  • 6

1 Answers1

7

You try to use a Comparator<Map.Entry<Integer, Integer>> on List<Integer> returned by values()

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

You need to use this comparator on a Set<Map.Entry<Integer, Integer>> which can be returned by entrySet() :

List<Map.Entry<Integer, Integer>> list = followLikeCount.entrySet()
                                                    .stream()
                                                    .sorted(Map.Entry.comparingByValue())
                                                    .collect(Collectors.toList());

If you want to get only the values, sorted, you can change the Comparator and get back a List<Integer> :

List<Integer> list = followLikeCount.values()
            .stream()
            .sorted(Comparator.naturalOrder())
            .collect(Collectors.toList());
azro
  • 53,056
  • 7
  • 34
  • 70
  • 1
    If you only want to get the sorted (`Comparable`) values, you can even do with a comparator, `followLikeCount.values() .stream() .sorted() .collect(Collectors.toList());`. Or without Streams: `List list = new ArrayList<>(followLikeCount.values()); list.sort(null);` – Holger Sep 18 '17 at 07:04