What is the best way get the symmetric difference

2019-01-05 03:36发布

I'm wondering if there is a quick/clean way to get the symmetric difference between two sets ?

I have:

Set<String> s1 = new HashSet<String>();
s1.add("a");
s1.add("b");
s1.add("c");

Set<String> s2 = new HashSet<String>();
s2.add("b");

I need something like:

Set<String> diff = Something.diff(s1, s2);
// diff would contain ["a", "c"]

Just to clarify I need the symmetric difference.

7条回答
\"骚年 ilove
2楼-- · 2019-01-05 03:59

You want the symmetric difference.

public static <T> Set<T> diff(final Set<? extends T> s1, final Set<? extends T> s2) {
    Set<T> symmetricDiff = new HashSet<T>(s1);
    symmetricDiff.addAll(s2);
    Set<T> tmp = new HashSet<T>(s1);
    tmp.retainAll(s2);
    symmetricDiff.removeAll(tmp);
    return symmetricDiff;
}

If you want a library, Apache Commons CollectionUtils has

CollectionUtils.disjunction(s1, s2)

which returns a non-generic Collection.

and Guava Sets has

Sets.symmetricDifference(s1, s2)

which returns an unmodifiable Set as a generic Sets.SetView.

Guava is a bit more modern, supporting generics, but either of these will work.

查看更多
登录 后发表回答