Search code examples
javacollectionsguavamultimap

How to iterate two multi maps and print the difference in file?


I have two multimaps as below :

ListMultimap<String, String> source_multimap = ArrayListMultimap.create();
ListMultimap<String, String> target_multimap = ArrayListMultimap.create();

for (SwiftTagListBlock s : source_tagListBlock) {
    Iterator<Tag> sourcetag_iterator = s.tagIterator();

    while (sourcetag_iterator.hasNext()) {
        Tag tag = (Tag) sourcetag_iterator.next();
        source_multimap.put(tag.getName(), tag.getValue());
    }
}
for (SwiftTagListBlock t : target_tagListBlock) {
    Iterator<Tag> targettag_iterator = t.tagIterator();

    while (targettag_iterator.hasNext()) {
        Tag tag = (Tag) targettag_iterator.next();
        target_multimap.put(tag.getName(), tag.getValue());
    }
}

It will give us pair of key-value with single-keys and multiple-values. I want to compare like this below :

if(mulimap1.get(key).equals(multimap2.get(key))) then compare the collection for values. if(multimap1.getValues()!=multimap2.getValues()) then print the values different.


Solution

  • Sets.intersection(source_multimap.keySet(), target_multimap.keySet()).forEach(key -> {
        Multiset<String> multiset1 = ImmutableMultiset.copyOf(source_multimap.get(key));
        Multiset<String> multiset2 = ImmutableMultiset.copyOf(target_multimap.get(key));
        System.out.println(key + " has values different: " + Multisets.union(
                Multisets.difference(multiset1, multiset2),
                Multisets.difference(multiset2, multiset1)
        ));
    });
    

    Example output:

    source: {a=[1, 1], b=[1]}
    target: {a=[1, 2], b=[1, 2], c=[1]}
    a has values different: [1, 2]
    b has values different: [2]
    

    And if you want to include differences for keys unique to either map substitute Sets.intersection with Sets.union:

    source: {a=[1, 1], b=[1]}
    target: {a=[1, 2], b=[1, 2], c=[1]}
    a has values different: [1, 2]
    b has values different: [2]
    c has values different: [1]