按值反转排序Map <String,Long>

pri*_*ain 5 sorting dictionary java-8 java-stream

我有一个Map<String, Long> map我希望Long使用Java 8的功能按相反顺序排序的值.使用Google我发现这个线程提供了这个解决方案

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

如果我想在评论中将订单反转,则表示要使用comparing(Entry::getValue).reversed()而不是comparing(Entry::getValue).

但是,代码不起作用.但是通过这种小小的适应性,它可以:

Map<String, Long> sortedMap = map.entrySet().stream()
          .sorted(Comparator.comparing(Entry::getValue))
                .collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                      (e1, e2) -> e1, LinkedHashMap::new));
Run Code Online (Sandbox Code Playgroud)

我是否必须先进行一些导入才能运行原始代码?

从那以后,仍然有什么可以得到颠倒的顺序

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));
Run Code Online (Sandbox Code Playgroud)

给出了一条错误信息:

The type Map.Entry does not define getValue(Object) that is applicable here
Run Code Online (Sandbox Code Playgroud)

Hol*_*ger 9

正如在这个答案中所解释的,当您链接方法调用时,Java 8的类型推断达到了极限Comparator.comparing(Entry::getValue).reversed().

相反,当使用类似的嵌套调用时Collections.reverseOrder(Comparator.comparing(Entry::getValue)),它将起作用.

当然,你可以使用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));
Run Code Online (Sandbox Code Playgroud)

但应该注意的是,当您忘记import static语句(即无法找到该方法)并将其与lambda表达式或方法引用结合使用时,编译器喜欢提供误导性错误消息.


最后要注意的,还有现有的比较器的实现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));
Run Code Online (Sandbox Code Playgroud)

要么

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