如何获得Java两个地图之间的区别?

2022-09-03 03:56:47

我有两张地图,如下所示:

Map<String, Record> sourceRecords;
Map<String, Record> targetRecords;

我想得到与每个地图不同的键。

  1. 它显示映射键在源记录中可用,但在目标记录中不可用。
  2. 它显示映射键在 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);
            }
        }

我能够找到公共键,但找不到不同的键。请帮忙。


答案 1

您可以使用番石榴Maps.difference(Map<K,V>左,Map<K,V>右)方法。它返回一个 MapDifference 对象,该对象具有用于获取所有四种映射条目的方法:

  • 在左右地图中同样存在
  • 仅在左侧地图中
  • 仅在右侧地图中
  • 键存在于两个映射中,但具有不同的值

因此,在您的情况下,只需3行代码即可解决:

MapDifference<String, Record> diff = Maps.difference(sourceRecords, targetRecords);
Set<String> keysOnlyInSource = diff.entriesOnlyOnLeft().keySet();
Set<String> keysOnlyInTarget = diff.entriesOnlyOnRight().keySet();

答案 2

集还允许您删除元素。

如果生成“帮助程序”集对您来说不是问题(因为条目太多;那么:

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

你可以从这里开始工作...