将 HashMap 排序为 TreeMap:自定义 Comparator 删除具有相同键的值

Sorting HashMap into TreeMap: custom Comparator removes values with the same key

我正在尝试对 HashMap<String, Long> 进行排序。我有以下排序代码:

private static class ValueComparator implements Comparator<String>{
            HashMap<String, Long> map = new HashMap<String, Long>();

            public ValueComparator(HashMap<String, Long> map){
                this.map.putAll(map);
            }

            @Override
            public int compare(String s1, String s2) {
                if(map.get(s1) > map.get(s2)){
                    System.out.println("s1: " + s1 + "; s2: " + s2);
                    return -1;
                }
                else if (map.get(s1).equals(map.get(s2))) {
                    return 0;
                }
                else{
                    return 1;
                }
            }
        }

private static TreeMap<String, Long> sortMapByValue(HashMap<String, Long> map){
                Comparator<String> comparator = new ValueComparator(map);
                //TreeMap is a map sorted by its keys.
                //The comparator is used to sort the TreeMap by keys.
                TreeMap<String, Long> result = new TreeMap<String, Long>(comparator);
                result.putAll(map);

                System.out.println("DONE sort");
                return result;
        }

问题是,当几个不同的键具有相同的值时,只有一个键进入最终映射:

示例:

 public class Test  {
    public static void main(String[] args)  {
        HashMap<String, Long> hashMap = new HashMap<>();
        hashMap.put("Cat", (long) 4);
        hashMap.put("Human", (long) 2);
        hashMap.put("Dog", (long) 4);
        hashMap.put("Fish", (long) 0);
        hashMap.put("Tree", (long) 1);
        hashMap.put("Three-legged-human", (long) 3);
        hashMap.put("Monkey", (long) 2);

        System.out.println(hashMap);  //7 pairs

        System.out.println(sortMapByValue(hashMap));  //5 pairs
   }
}

我该如何解决?

我认为您以非预期的方式使用地图并违反合同是无法解决的。树图期望按键排序,键应该是唯一的,因此当比较 == 0 时,它只会覆盖节点的值。你总是可以实现你自己的 TreeMap 并让它做任何你想做的事情。

我不确定你想用它做什么,但我认为你需要

TreeMap<Long,List<String>>

http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/TreeMap.java

    if (cpr != null) {
        do {
            parent = t;
            cmp = cpr.compare(key, t.key);
            if (cmp < 0)
                t = t.left;
            else if (cmp > 0)
                t = t.right;
            else
                return t.setValue(value);
        } while (t != null);