按值反转排序Map <string,long =“”>

时间:2015-05-06 17:03:27

标签: sorting dictionary java-8 java-stream

我有一个Map<String, Long> map,我希望使用Java 8的功能按相反顺序排序Long。使用Google我发现this thread提供此解决方案

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

如果我想在评论中颠倒订单,则说明使用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));

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

由于

,还有什么可以得到颠倒的顺序
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));

给出了一条错误消息:

The type Map.Entry does not define getValue(Object) that is applicable here

1 个答案:

答案 0 :(得分:8)

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

相反,当使用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语句(即无法找到该方法)并将其与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));

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