Sort Map<String, Long> by value reversed

放肆的年华 提交于 2019-12-03 17:00:49
Holger

As explained in this answer, the type inference of Java 8 hit its limit when you chain 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));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!