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

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

   }

}

我将如何修复它?


杨__羊羊
浏览 192回答 1
1回答

POPMUISE

我认为您以非预期的方式使用地图并违反合同是不可修复的。树图期望按键排序,键应该是唯一的,所以当比较 == 0 时,它只会覆盖节点的值。你总是可以实现你自己的 TreeMap 并让它做你想做的任何事情。我不确定你想用它做什么,但我认为你需要像TreeMap<Long,List<String>>http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/TreeMap.java&nbsp; &nbsp; if (cpr != null) {&nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; parent = t;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cmp = cpr.compare(key, t.key);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (cmp < 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; t = t.left;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else if (cmp > 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; t = t.right;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return t.setValue(value);&nbsp; &nbsp; &nbsp; &nbsp; } while (t != null);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java