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?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With