如何用整数值对散列图进行排序 [英] How to sort a hashmap by the Integer Value
本文介绍了如何用整数值对散列图进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("a", 4);
map.put("c", 6);
map.put("b", 2);
期望的输出(HashMap):
Desired output(HashMap):
c : 6
a : 4
b : 2
我无法找到任何有关按价值降序的信息。
如何实现? (Extra class not preferred)
I haven't been able to find anything about Descending the order by value.
How can this be achieved? (Extra class not preferred)
推荐答案
试试这个:
Try this:
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 4);
map.put("c", 6);
map.put("b", 2);
Object[] a = map.entrySet().toArray();
Arrays.sort(a, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Map.Entry<String, Integer>) o2).getValue()
.compareTo(((Map.Entry<String, Integer>) o1).getValue());
}
});
for (Object e : a) {
System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : "
+ ((Map.Entry<String, Integer>) e).getValue());
}
输出:
output:
c : 6
a : 4
b : 2
这篇关于如何用整数值对散列图进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文