我有两张地图如下:
Map<String, Record> sourceRecords;
Map<String, Record> targetRecords;
我想让每个地图都有不同的关键字.i.e。
我按照以下方式做到了:
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);
}
}
我能够找到公共密钥但不能找到不同的密钥。请帮忙。
答案 0 :(得分:17)
您可以使用Guava的Maps.difference(Map<K, V> left, Map<K, V> right)
方法。它返回一个MapDifference
对象,该对象具有获取所有四种映射条目的方法:
因此,在您的情况下,只需3行代码即可解决:
MapDifference<String, Record> diff = Maps.difference(sourceRecords, targetRecords);
Set<String> keysOnlyInSource = diff.entriesOnlyOnLeft().keySet();
Set<String> keysOnlyInTarget = diff.entriesOnlyOnRight().keySet();
答案 1 :(得分:7)
设置允许您删除元素。
如果生成“帮助”集对你来说不是问题(因为条目太多;那么:
Set<String> sources = get a copy of all source entries
Set<String> targets = get a copy of all source entries
然后:
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
你可以从这里开始工作......
答案 2 :(得分:4)
您可以使用副本Set
和removeAll
:
Set<String> difference = new HashSet<String>(sourceKeysList);
difference.removeAll(targetKeysList);
答案 3 :(得分:0)
sourceKeysList.removeAll(targetKeysList)
targetKeysList.removeAll(sourceKeysList)