Sort Map <String, Long> by Reverse Value

I have Map<String, Long> mapone that I want to sort by value Longin reverse order using Java 8 functions. With Google, I found this topic that 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 the order to be canceled in the comments, it says use comparing(Entry::getValue).reversed()instead comparing(Entry::getValue).

However, the code does not work. But with this small adaptation, he 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 need to import first to be able to run the source code?

What else remains to get the reverse 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 error message:

The type Map.Entry does not define getValue(Object) that is applicable here
+4
source share
1 answer

, Java 8 , , , Comparator.comparing(Entry::getValue).reversed().

, , Collections.reverseOrder(Comparator.comparing(Entry::getValue)), .

, static import s:

Map<String, Long> sortedMap = map.entrySet().stream()
    .sorted(reverseOrder(comparing(Entry::getValue)))
    .collect(toMap(Entry::getKey, Entry::getValue,
          (e1, e2) -> e1, LinkedHashMap::new));

, , import static (.. can not found) - .


Map.Entry.comparingByValue() Map.Entry.comparingByValue(Comparator),

Map<String, Long> sortedMap = map.entrySet().stream()
    .sorted(reverseOrder(comparingByValue()))
    .collect(toMap(Entry::getKey, Entry::getValue,
          (e1, e2) -> e1, LinkedHashMap::new));

Map<String, Long> sortedMap = map.entrySet().stream()
    .sorted(comparingByValue(reverseOrder()))
    .collect(toMap(Entry::getKey, Entry::getValue,
          (e1, e2) -> e1, LinkedHashMap::new));
+8

All Articles