【问题标题】:Sort Map<String, Long> by value reversed按反转的值对 Map<String, Long> 进行排序
【发布时间】:2015-07-16 23:15:29
【问题描述】:

我有一个 Map&lt;String, Long&gt; 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));

如果我想在 cmets 中颠倒顺序,它说使用 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

【问题讨论】:

标签: sorting dictionary java-8 java-stream


【解决方案1】:

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

相比之下,当使用像Collections.reverseOrder(Comparator.comparing(Entry::getValue)) 这样的嵌套 调用时,它会起作用。

当然,你可以使用staticimports:

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));

【讨论】:

    猜你喜欢
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 2021-03-26
    • 2023-04-07
    相关资源
    最近更新 更多