如何按整数值对哈希图进行排序[重复]

2024-04-19

HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("a", 4);
map.put("c", 6);
map.put("b", 2);

期望的输出(HashMap):

c : 6
a : 4
b : 2

我还没有找到任何有关按值降序的信息。
如何才能实现这一目标? (不推荐额外课程)


尝试这个:

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何按整数值对哈希图进行排序[重复] 的相关文章

随机推荐