java HashMap 排序 <String,Integer> 。如何排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12229577/
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
java HashMap sorting <String,Integer> . How to sort it?
提问by Hardik
Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?
In my project, I have taken a HashMap like this
在我的项目中,我采用了这样的 HashMap
HashMap degree = new HashMap();
HashMap 度数 = new HashMap();
Suppose I have:
假设我有:
degree.put("a",5);
degree.put("b",2);
degree.put("c",4);
degree.put("d",2);
degree.put("e",3);
degree.put("f",5);
Now I have to Sort this list according to given Integer values
现在我必须根据给定的整数值对这个列表进行排序
Sorted HashMap Should be :
排序的 HashMap 应该是:
{a=5, f=5, c=4, e=4, b=4, d=2}
{a=5, f=5, c=4, e=4, b=4, d=2}
How I can do this ?
我怎么能做到这一点?
回答by bmargulies
A HashMap
is an unorderedcollection. It has no sort order. Even a TreeMap
will sort by key, not value.
AHashMap
是一个无序集合。它没有排序顺序。甚至 aTreeMap
将按键排序,而不是按值排序。
If you want to prepare a sorted list by the sort order of the values, you'll have to create an appropriate object, such as an ArrayList<Map.Entry<String,Integer>>
, iterate over your HashMap
and insert all the entries, and then call Collections.sort
with a collation function.
如果您想按值的排序顺序准备一个排序列表,您必须创建一个适当的对象,例如ArrayList<Map.Entry<String,Integer>>
,迭代您HashMap
并插入所有条目,然后Collections.sort
使用排序规则调用。
回答by La bla bla
If you want sorted map, HashMap isn't the best approach.
如果你想要排序地图,HashMap 不是最好的方法。
I'd suggest taking a look at TreeMap
as it is sorted. You can set the comparator to compare the values instead of the keys, as they do in this answer:
我建议看一下,TreeMap
因为它是排序的。您可以设置比较器来比较值而不是键,就像他们在这个答案中所做的那样:
回答by user1438021
ArrayList<Integer> sortedHashMap=new ArrayList<Integer>();
for("your Object" m : degree.values())
{
sortedHashMap.add(m);
}
collections.sort(sortedHashMap);
so ,you can print your hashMap as sorted hashMap!
因此,您可以将 hashMap 打印为已排序的 hashMap!
回答by huseyin tugrul buyukisik
You can do insertion sortto build a new hashmap from the original(takes x2 memory and is very inefficient). So, you will need to use .get() and .set() methods of the hashmap nearly n*n(worst case) times where n is the number of elements.
您可以进行插入排序以从原始哈希图构建新的哈希图(占用 x2 内存并且效率非常低)。因此,您将需要使用哈希图的 .get() 和 .set() 方法近 n*n(最坏情况)次,其中 n 是元素的数量。