Rob*_*bot 12 java collections set
我有两张地图如下:
Map<String, Record> sourceRecords;
Map<String, Record> targetRecords;
Run Code Online (Sandbox Code Playgroud)
我想让每个maps.ie的键都不同
我做了如下:
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();
Run Code Online (Sandbox Code Playgroud)
编辑
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我能够找到公共密钥但不能找到不同的密钥.请帮忙.
Phi*_*ler 20
你可以使用番石榴的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();
Run Code Online (Sandbox Code Playgroud)
集也允许您删除元素.
如果生成"帮助"集对你来说不是问题(因为条目太多;那么:
Set<String> sources = get a copy of all source entries
Set<String> targets = get a copy of all source entries
Run Code Online (Sandbox Code Playgroud)
然后:
sources.removeAll(targets) ... leaves only entries in sources that are only in sources, not in target
Run Code Online (Sandbox Code Playgroud)
而
sources.retainAll(targets) ... leaves only entries that are in both sets
Run Code Online (Sandbox Code Playgroud)
你可以从这里开始工作......
您可以使用副本Set并且removeAll:
Set<String> difference = new HashSet<String>(sourceKeysList);
difference.removeAll(targetKeysList);
Run Code Online (Sandbox Code Playgroud)
查看设置界面