Sort Map<String, Long> by value reversed

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

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 

回答1:

As explained in this answerchain method invocations like in Comparator.comparing(Entry::getValue).reversed().

In contrast, when using nested invocations like in Collections.reverseOrder(Comparator.comparing(Entry::getValue)) it will work.

Of course, you can use static imports:

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

but it should be noted that the compiler likes to provide misleading error messages when you forget an import static statement (i.e. the method can’t be found) and combine it with lambda expressions or method references.


As a final note, there are also the existing comparator implementations Map.Entry.comparingByValue() and Map.Entry.comparingByValue(Comparator) which allow you to use

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

or

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!