java – 使用新比较器时的TreeMap putall问题

TreeMap<String, Integer> map1 = new TreeMap<String, Integer>();
map1.put("A", 1); map1.put("B", 2); map1.put("C", 3);
TreeMap<String, Integer> map2 = new TreeMap<>((str1, str2) -> map1.get(str1) - map1.get(str2) > 0 ? -1 : 1);
map2.putAll(map1);
Iterator<String> iterator = map2.keySet().iterator();
    while(iterator.hasNext()) {
        String key = iterator.next();
        System.out.println(key + "  " + map2.get(key) + " " + map1.get(key));
}

输出是

C  null 3

B  null 2

A  null 1

请解释为什么我从map2获取空值,即使在执行map2.putAll(map1)之后

奇怪的是,当我遍历条目时,迭代器正在给出正确的输出

    Iterator<Entry<String, Integer>> entryIterator = map2.entrySet().iterator();
    while(entryIterator.hasNext()) {
        Entry<String, Integer> entry = entryIterator.next();
        System.out.println(entry.getKey() + " " + entry.getValue());
    }

编辑
正如所回答的问题是与比较它正在与之合作

    TreeMap<String, Integer> map2 = new TreeMap<>((str1, str2) -> str1.equals(str2) ? 0 : map1.get(str1) - map1.get(str2) > 0 ? -1 : 1);

最佳答案 当映射值相等时,您错过了在比较器中返回零:

TreeMap<String, Integer> map2 = new TreeMap<>(
    new Comparator<String>() {

        @Override
        public int compare(String str1, String str2) {
            if(map1.get(str1).equals(map1.get(str2))) {
                return 0;
            }
            return map1.get(str1) - map1.get(str2) > 0 ? -1 : 1;
        }
    });

TreeMap的文档:

Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

点赞