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

心已入冬 提交于 2019-12-25 07:40:02

问题


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.


回答1:


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]


来源:https://stackoverflow.com/questions/37025495/how-to-iterate-two-multi-maps-and-print-the-difference-in-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!