【发布时间】:2015-10-19 23:03:55
【问题描述】:
我有一个 LinkedHashMap> 我想根据键值大小的降序对键进行排序。我目前有来自另一个线程的这个片段,但我不确定如何更改它以适用于我的案例。
myMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(x,y) -> {throw new AssertionError();},
LinkedHashMap::new
));
这是我尝试过的
List<Map.Entry<String, Integer>> entries =
new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> a, Map.Entry<String,Integer> b){
return a.getValue().size().compareTo(b.getValue().size());
}
});
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
我刚刚在其中添加了 .size()。我从这个线程中找到了它。我指的大小是 HashSet 中的项目数。它通常只是 getValue().size() 但在这里不起作用。
【问题讨论】:
-
我尝试实现他们对 (o1.getValue().size()).compareTo(o2.getValue().size()) 所做的事情,但没有成功。我不确定如何比较值的大小是我的问题。
-
没有您在帖子中尝试过的任何内容。请通过编辑和引用其他答案来添加它。实际上,我会说您并没有理解该代码片段中发生了什么。你应该试着分析一下。还请澄清“
... the size of their values”(这是否意味着字符串长度?)编辑您的帖子!
标签: java hashmap comparator