我有两个多图,如下所示:

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


它将为我们提供一对具有单键和多值的键值。我想这样比较:

if(mulimap1.get(key).equals(multimap2.get(key)))然后比较集合的值。 if(multimap1.getValues()!= multimap2.getValues())然后输出不同的值。

最佳答案

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


输出示例:

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]


并且,如果您想为映射替换Sets.intersectionSets.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]

08-04 21:16