How do I get the difference between two Java maps?

I have two maps as follows:

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

I want every map i. The keys of E are different

>It displays the mapping keys available in sourcerecords, but not in targetrecords. > It displays the mapping keys available in targetrecords, but not in sourcerecords

I did the following:

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

edit

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 can find a public key, but I can't find a different key Please help.

Solution

Sets also allow you to delete elements

If generating a help set is not a problem for you (because there are too many entries; then:

Set<String> sources = get a copy of all source entries
Set<String> targets = get a copy of all source entries

then:

sources.removeAll(targets) ... leaves only entries in sources that are only in sources,not in target

and

sources.retainAll(targets) ... leaves only entries that are in both sets

You can start working here

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>