Java 如何按整数值对哈希图进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21054415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:13:40  来源:igfitidea点击:

How to sort a hashmap by the Integer Value

javahashmap

提问by GameDevGuru

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

Desired output(HashMap):

期望输出(HashMap):

c : 6
a : 4
b : 2

I haven't been able to find anything about Descending the order by value.
How can this be achieved? (Extra class not preferred)

我找不到任何关于按值降序的信息。
如何做到这一点?(不推荐加班)

采纳答案by Evgeniy Dorofeev

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

回答by nKn

One of the characteristics of the Hashelements is their particular speed on doing operations like adding, deleting and so on, and this is precisely because they use Hash algorhythms, which means they doesn't keep the order of elements that we know as ascendant or descendant. That means that with the Hashdata structures you won't achieve what you want.

Hash元素的特点之一是它们在进行添加、删除等操作时的特殊速度,这正是因为它们使用了哈希算法,这意味着它们不保持我们所知道的元素的升序或降序顺序. 这意味着使用Hash数据结构您将无法实现您想要的。

回答by Joseph Martin

You can't explicity sort the HashMap, but can sort the entries. Maybe something like this helps:

您不能明确地对 HashMap 进行排序,但可以对条目进行排序。也许这样的事情有帮助:

// not yet sorted
List<Integer> intList = new ArrayList<Integer>(map.values());

Collections.sort(intList, new Comparator<Integer>() {

    public int compare(Integer o1, Integer o2) {
        // for descending order
        return o2 - o1;
    }
});