How to get the difference between two maps Java?(如何获得两个地图Java之间的差异?)
问题描述
我有两张地图如下:
Map<String, Record> sourceRecords;
Map<String, Record> targetRecords;
我想获得与每个地图不同的键.即
I want to get the keys differ from each of the maps.i.e.
- 它显示 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);
}
}
我能够找到公共键,但不能找到不同的键.请帮忙.
I am able to find the common keys but not distinct keys. Please help.
推荐答案
集合也允许您删除元素.
如果生成帮助"集对您来说不是问题(因为条目太多;那么:
If generating "helper" sets is not a problem for you (because of too many entries; what about:
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
您可以从这里开始工作......
You can work your way from here ...
这篇关于如何获得两个地图Java之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获得两个地图Java之间的差异?
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01