Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a Hashmap by Value in Java 8 [duplicate]

Tags:

java

java-8

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?

like image 287
Bryn Avatar asked Mar 08 '23 01:03

Bryn


1 Answers

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());
like image 118
azro Avatar answered Mar 19 '23 21:03

azro