java - 基于 Value 然后 Key 对 HashMap 进行排序?

标签 java sorting hashtable hashmap

<分区>

Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?

我有一个 HashMap 类型:

HashMap<String, Integer> h = new HashMap<String, Integer>();

HashMap 包含一个字符串列表,Integer 是一个计数器,表示已找到该字符串的次数。我希望能够做的是根据整数对 HashMap 进行排序,然后根据字符串的字母顺序进行排序。

目前我正在记录一个单词的最大出现次数(名为 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--;
    }
}

它不按字母顺序对值进行排序,它还会访问 HashMap max*h(size) 次。

什么是更好的解决方案?

最佳答案

这是一个 Comparator,它使用 Comparable 键和值对 Map.Entry 对象进行排序:

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());
        }
    }

}

您可以将所有 map 条目放入一个列表中,然后对其进行排序:

List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(h.entrySet());
Collections.sort(list, new ValueThenKeyComparator<String, Integer>());

关于java - 基于 Value 然后 Key 对 HashMap 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3074154/

相关文章:

java - 无法从 okhttp 导入请求和响应类

java - 从 servlet 检索文件路径

c++ - 排序元素,但保持某些元素固定

java - 如何访问哈希表中的值

java - 停止/杀死 Java 中的所有线程

java - LWJGL Assimp : Loading Textures

c - 不具有唯一字符的字典顺序排列

.net - 仅在 XAML 中更改 ListView 排序属性/方向

Powershell 哈希表计数和键属性重载

c++ - 如何以 O(1) 的时间从 C++ 哈希表中随机检索元素