【发布时间】:2015-07-16 23:15:29
【问题描述】:
我有一个 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));
如果我想在 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
【问题讨论】:
-
@Misha 我认为这个帖子更适合stackoverflow.com/questions/27205309/…。这里的问题是该类型不能很好地与
Comparator.comparing(Entry::getValue).reversed()一起传播(尽管您链接的线程中的解决方案可以工作并且更好)。
标签: sorting dictionary java-8 java-stream