【发布时间】:2018-05-22 11:03:52
【问题描述】:
我只需要找到两张地图之间的差异,而差异可能是缺少键或键值不同。
我找到了Differences between maps 的一般答案
sources.removeAll(targets) ... leaves only entries in sources that are only in sources, not in target而
sources.retainAll(targets) ... leaves only entries that are in both sets
但我不确定它是否比下面的代码更好,因为除了键存在之外我还需要检查值是否不同
Map<K, V> updatedMap = new EnumMap<>(K.class);
for (Map.Entry<K, V> finalSet : secondMap.entrySet()) {
K currentKey = finalSet.getKey();
if (!firstMap.containsKey(currentKey) || firstMap.get(currentKey) != finalSet.getValue()) {
updatedMap.put(currentKey, finalSet.getValue());
firstMap.remove(currentKey);
}
}
for (Map.Entry<K, V> currentSet : firstMap.entrySet()) {
K currentKey = currentSet.getKey();
if (!secondMap.containsKey(currentKey)) {
updatedMap.put(currentKey, currentSet.getValue());
} else if (secondMap.get(currentKey) != currentSet.getValue()) {
updatedMap.put(currentKey, secondMap.get(currentKey));
}
}
他们是找到包括值在内的地图之间差异的更好方法吗?
【问题讨论】:
-
.entrySet()和使用番石榴Sets.symmetricDifference怎么样? -
@Eugene 我目前不用番石榴,不过你可以回答
-
在我这样做之前假设
leftMap = [{1, "one"}, {2, "two"}]和rightMap = [{1, "uno"}, {2, "duo"}]你有什么预期的结果?[{2=two}, {1=one}, {2=duo}, {1=uno}]? -
@Eugene 仅来自 secondMap [{2=uno}, {1=duo}] 的值
标签: java