【问题标题】:Sorting HashMap into TreeMap: custom Comparator removes values with the same key将HashMap排序为TreeMap:自定义Comparator删除具有相同键的值
【发布时间】:2018-10-07 01:07:45
【问题描述】:

我正在尝试对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
   }
}

我该如何解决?

【问题讨论】:

    标签: java hashmap comparator


    【解决方案1】:

    我认为您以无意的方式使用地图并违反合同是无法解决的。树形图期望按键排序,并且键应该是唯一的,因此当比较 == 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);
    

    【讨论】:

      猜你喜欢
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 2017-03-22
      • 1970-01-01
      相关资源
      最近更新 更多