I have a Map<String, Long> map
which I want to sort by the Long
value in reversed order using the features of Java 8. With Google I found this thread which provides this solution
Map<String, Long> sortedMap = map.entrySet().stream()
.sorted(comparing(Entry::getValue))
.collect(toMap(Entry::getKey, Entry::getValue,
(e1,e2) -> e1, LinkedHashMap::new));
If I want to have the order reversed in the comments it says to use comparing(Entry::getValue).reversed()
instead of comparing(Entry::getValue)
.
However, the code doesn't work. But with this little adaption it does:
Map<String, Long> sortedMap = map.entrySet().stream()
.sorted(Comparator.comparing(Entry::getValue))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
Do I have to do some imports first to be able to run the original code?
What still remains to get the reversed order, since
Map<String, Long> sortedMap = map.entrySet().stream()
.sorted(Comparator.comparing(Entry::getValue).reversed())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
gives my an error message:
The type Map.Entry does not define getValue(Object) that is applicable here