java - 在 Java 中对 HashMap 值进行排序不返回正确的顺序

标签 java sorting hashmap

我在排序时遇到了一些问题 HashMaps值在 Java 中. 我的代码是:

 @SuppressWarnings("unchecked")
          Map<String, Integer> scores = ((HashMap<String, Integer>) prefs.get());
          Map<String, Integer> sortedscores = sortByValues(scores);
          printMap(scores);
          System.out.println("==============");
          printMap(sortedscores);

prefs.get() 返回一个 Map<String, ?>我将其转换为 <String, Integer >

排序函数:

public static <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
    Comparator<K> valueComparator =  new Comparator<K>() {
        public int compare(K k1, K k2) {
            int compare = map.get(k2).compareTo(map.get(k1));
            if (compare == 0) return 1;
            else return compare;
        }
    };
    Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);
    return new LinkedHashMap<K,V>(sortedByValues);
}
public static void printMap(Map<String, Integer> unsortMap){
    for (Map.Entry entry : unsortMap.entrySet()) {
        System.out.println("Key : " + entry.getKey() 
                               + " Value : " + entry.getValue());
    }
}

输出是:

Key : John Doe Value : 1000
Key : balazs Value : 975
Key : Balazs Value : 900
Key : aladar Value : 975
Key : balazs2 Value : 975
Key : score Value : 1000
Key : house Value : 1037
==============
Key : balazs Value : 975
Key : aladar Value : 975
Key : balazs2 Value : 975
Key : Balazs Value : 900
Key : house Value : 1037
Key : John Doe Value : 1000
Key : score Value : 1000

第一个是未排序的,第二个是排序的。 我的问题是第二个输出不是按 DESC 顺序(按值)

编辑: 如果我自己创建一个 hasmap,它工作正常:

Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("asd", 1);
        unsortMap.put("asd2r1", 5);
        unsortMap.put("house", 7);
        unsortMap.put("3", 124);
        unsortMap.put("7", 4);
        unsortMap.put("5", 6);
        unsortMap.put("6", 2);
        unsortMap.put("8", 0);

但如果我用这个试试:Map<String, Integer> scores = ((HashMap<String, Integer>) prefs.get());我得到了那个奇怪的命令。

最佳答案

你的比较器看起来不符合 specification :

        int compare = map.get(k2).compareTo(map.get(k1));
        if (compare == 0) return 1;
        else return compare;

为什么当两个条目相等时返回 1?

关于java - 在 Java 中对 HashMap 值进行排序不返回正确的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15660473/

相关文章:

javascript - jquery tablesorter 如何用图像对表格进行排序

java - 在 JRE 中使用什么算法将 ArrayList<T> 转换为 LinkedHashSet<T>

c++ - tbb 并发 HashMap 作为结构的成员

java - 方便地在 enum 和 int/String 之间映射

java - 尝试按字母顺序显示数组时出错

java - Phonegap相机拍照

c - 查找排序数组中元素的索引,如果未找到,则打印应插入的位置的索引

java - HashMap 空间问题

java - 如何编写一个java函数来返回动态类型的数组?

java - 如何在不依赖数据库的 webapp 部署之间保存服务器状态?