如何获得两个映射Java之间的区别? [英] How to get the difference between two maps Java?

查看:139
本文介绍了如何获得两个映射Java之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两张地图如下:

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

我想获得每个maps.i.e的密钥不同。

I want to get the keys differ from each of the maps.i.e.


  1. 它显示sourceRecords中可用的映射键,但不显示targetRecords中的映射键。

  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);
            }
        }

我能找到公共密钥但不能区分键。请帮助。

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之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆