问题描述
可能的重复:
如何对地图进行排序<键、值>关于 Java 中的值?
我有一个 HashMap 类型:
I have a HashMap of the type:
HashMap<String, Integer> h = new HashMap<String, Integer>();
HashMap 包含一个字符串列表,而 Integer 是一个计数器,用于计算找到该字符串的次数.我想做的是根据整数对 HashMap 进行排序,然后根据字符串的字母顺序.
The HashMap contains a list of Strings and the Integer is a counter for the number of times that String has been found. What I would like to be able to do is sort the HashMap based on the Integers, then on the alphabetical order of the Strings.
目前我正在记录一个单词的最大出现次数(名为 max 的变量)并显示如下值:
At the moment I am keeping a record of the largest occurrence of a word (variable named max) and displaying the values as follows:
public void print(){
while(max > 0){
for (String key : h.keySet()){
if(h.get(key) == max){
System.out.println(key + " " + h.get(key));
}
}
max--;
}
}
它不按字母顺序对值进行排序,它也访问 HashMap max*h(size) 次.
Which doesn't sort the values alphabetically, also it accesses the HashMap max*h(size) times.
什么是更好的解决方案?
What is the better solution?
推荐答案
这是一个 Comparator
,它使用 Comparable
键对 Map.Entry
对象进行排序和价值观:
Here's a Comparator
that sorts Map.Entry
objects with Comparable
keys and values:
public class ValueThenKeyComparator<K extends Comparable<? super K>,
V extends Comparable<? super V>>
implements Comparator<Map.Entry<K, V>> {
public int compare(Map.Entry<K, V> a, Map.Entry<K, V> b) {
int cmp1 = a.getValue().compareTo(b.getValue());
if (cmp1 != 0) {
return cmp1;
} else {
return a.getKey().compareTo(b.getKey());
}
}
}
您将所有地图条目放入一个列表中,然后对其进行排序:
You'd put all of the map entries into a list and then sort that:
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(h.entrySet());
Collections.sort(list, new ValueThenKeyComparator<String, Integer>());
这篇关于根据值然后键对HashMap进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!