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. (SeeComparable
orComparator
for a precise definition of consistent with equals.) This is so because theMap
interface is defined in terms of theequals
operation, but a sorted map performs all key comparisons using itscompareTo
(orcompare
) 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 withequals
; it just fails to obey the general contract of theMap
interface.
关于java - 使用新比较器时 TreeMap putall 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31470169/