Search code examples
javacollectionsset

How to get the difference between two maps Java?


I have two maps as below :

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

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

  1. It shows mapping keys available in sourceRecords but not in targetRecords.
  2. It shows mapping keys available in targetRecords but not in sourceRecords.

I did it as below :

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 am able to find the common keys but not distinct keys. Please help.


Solution

  • Sets allow you to remove elements as well.

    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 target entries
    

    then:

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

    whereas

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

    You can work your way from here ...