如何获得Java两个地图之间的区别?
2022-09-03 03:56:47
我有两张地图,如下所示:
Map<String, Record> sourceRecords;
Map<String, Record> 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);
}
}
我能够找到公共键,但找不到不同的键。请帮忙。