Order HashMap< String,Integer>根据Integer [英] Order HashMap<String,Integer> according Integer
问题描述
可能存在重复:
如何对Map< Key,Value>进行排序关于Java中的值?
亲爱的
i有一个hash地图,其中我保存了tho值:歌手(字符串)和流行度(整数)。
现在,我想根据流行度来订购这个散列图。
在java中怎么做?
作为一个关键,以及(歌手)的受欢迎程度作为价值。 HashMap没有排序,而TreeMap是按键排序的,而不是按值排序的,所以它不会有帮助。
如果你需要歌手根据流行度排序,那么与地图中的所有歌手建立一个列表,然后使用比较两个歌手的流行度的比较器对这个列表进行排序:
列表与LT;字符串> singers = new ArrayList< String>(map.keySet());
Collections.sort(歌手,新比较器< String>(){
@Override
public int compare(String s1,String s2){
Integer1 = map.get s1);
Integer2 = map.get(s2);
return popularity1.compareTo(popular2);
}
});
Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?
Dear, i have an hash map, in which i have saved tho values: singer(string) and popularity(integer).
Now, i want order this hash map according the popularity.
How can do it in java?
I assume you store the singer as a key, and the popularity (of the singer) as value. A HashMap is not ordered, and a TreeMap is ordered by key, not by value, so it won't help.
If you need your singers ordered by popularity, then build a list with all the singers in the map, and then sort this list using a comparator which compares the popularity of both singers:
List<String> singers = new ArrayList<String>(map.keySet());
Collections.sort(singers, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
Integer popularity1 = map.get(s1);
Integer popularity2 = map.get(s2);
return popularity1.compareTo(popularity2);
}
});
这篇关于Order HashMap< String,Integer>根据Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!