我有两张 map 如下:
Map<String, Record> sourceRecords;
Map<String, Record> targetRecords;
我想获得与每个 map 不同的键。即
- 它显示在 sourceRecords 中可用但在 targetRecords 中不可用的映射键。
- 它显示了 targetRecords 中可用但 sourceRecords 中不可用的映射键。
我是这样做的:
Set<String> sourceKeysList = new HashSet<String>(sourceRecords.keySet());
Set<String> targetKeysList = new HashSet<String>(targetRecords.keySet());
SetView<String> intersection = Sets.intersection(sourceKeysList, targetKeysList);
Iterator it = intersection.iterator();
while (it.hasNext()) {
Object object = (Object) it.next();
System.out.println(object.toString());
}
SetView<String> difference = Sets.symmetricDifference(sourceKeysList, targetKeysList);
ImmutableSet<String> immutableSet = difference.immutableCopy();
编辑
if(sourceKeysList.removeAll(targetKeysList)){
//distinct sourceKeys
Iterator<String> it1 = sourceKeysList.iterator();
while (it1.hasNext()) {
String id = (String) it1.next();
String resultMessage = "This ID exists in source file but not in target file";
System.out.println(resultMessage);
values = createMessageRow(id, resultMessage);
result.add(values);
}
}
if(targetKeysList.removeAll(sourceKeysList)){
//distinct targetKeys
Iterator<String> it1 = targetKeysList.iterator();
while (it1.hasNext()) {
String id = (String) it1.next();
String resultMessage = "This ID exists in target file but not in source file";
System.out.println(resultMessage);
values = createMessageRow(id, resultMessage);
result.add(values);
}
}
我能够找到通用键但不能找到不同键。请帮忙。
最佳答案
您可以使用 Guava的 Maps.difference(Map<K, V> left, Map<K, V> right)
方法。它返回 MapDifference
对象,它具有获取所有四种映射条目的方法:
- 在左右 map 中均等出现
- 只在左图</li>
- 只在右图
- key 出现在两个映射中,但具有不同的值
所以在您的情况下,只需 3 行代码即可解决:
MapDifference<String, Record> diff = Maps.difference(sourceRecords, targetRecords);
Set<String> keysOnlyInSource = diff.entriesOnlyOnLeft().keySet();
Set<String> keysOnlyInTarget = diff.entriesOnlyOnRight().keySet();
关于java - 如何获得两个 map Java之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38015282/