java 根据值然后键对 HashMap 进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3074154/
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
Sorting a HashMap based on Value then Key?
提问by neut
Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?
I have a HashMap of the type:
我有一个 HashMap 类型:
HashMap<String, Integer> h = new HashMap<String, Integer>();
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.
HashMap 包含一个字符串列表,而 Integer 是该字符串被找到次数的计数器。我希望能够做的是根据整数对 HashMap 进行排序,然后根据字符串的字母顺序排序。
At the moment I am keeping a record of the largest occurrence of a word (variable named max) and displaying the values as follows:
目前,我正在记录出现最多的单词(名为 max 的变量)并显示如下值:
public void print(){
    while(max > 0){
       for (String key : h.keySet()){
           if(h.get(key) == max){
               System.out.println(key + " " + h.get(key));
           }
       }
       max--;
    }
}
Which doesn't sort the values alphabetically, also it accesses the HashMap max*h(size) times.
它不按字母顺序对值进行排序,它还访问 HashMap max*h(size) 次。
What is the better solution?
什么是更好的解决方案?
回答by Sean
Here's a Comparatorthat sorts Map.Entryobjects with Comparablekeys and values:
这是一个使用键和值对对象进行Comparator排序的方法:Map.EntryComparable
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>());
回答by Aravind Yarram
Look at Google Guava libraries. It has a Multisetwhich does the calculation for you and then you have Orderingclass that simplifies sorting.
看看谷歌番石榴库。它有一个Multiset为你做计算的Ordering类,然后你有一个简化排序的类。
All you need to do is to populate Multisetwith your strings. It will maintain the frequency for you. Then you can sort on those strings using Ordering.
您需要做的就是填充Multiset您的字符串。它将为您保持频率。然后,您可以使用 对这些字符串进行排序Ordering。
回答by Enno Shioji
Probably not the most elegant solution, but how about this?
可能不是最优雅的解决方案,但是这个怎么样?
//TreeSet with reversed natural ordering (big integers first)
Map<Integer, Set<String>> h = 
     new TreeMap<Integer, Set<String>>(Collections.reverseOrder());
//and use TreeSet for the set...
// ...    
// 
for(Map.Entry<Integer,Set<String>> entry : h.entrySet()){
    for(String str : entry.getValue()){
        System.out.println(str + " has occured " + entry.getKey() + " times.");
    }
}
回答by Shamal Karunarathne
you can use SortedMap interface to sort your HashMap. It's very easy - Automatic sorting. Refer to http://java.sun.com/j2se/1.4.2/docs/api/java/util/SortedMap.html. I didn't include any code here, but if you need, just add a comment. I'll give you a sample code.
您可以使用 SortedMap 接口对 HashMap 进行排序。这很容易 - 自动排序。请参阅http://java.sun.com/j2se/1.4.2/docs/api/java/util/SortedMap.html。我没有在这里包含任何代码,但如果您需要,只需添加注释。我会给你一个示例代码。

