javacollectionsset

What is the best way get the symmetric difference between two sets in java?


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.


Solution

  • You can use some functions from the Google Guava library (which is really great, I strongly recommend it!):

    Sets.difference(s1, s2);
    Sets.symmetricDifference(s1, s2);
    

    Javadocs for difference() and symmetricDifference()

    symmetricDifference() does exactly what you are asking for, but difference() is also often helpful.

    Both methods return a live view, but you can for example call .immutableCopy() on the resulting set to get a non-changing set. If you don't want a view, but need a set instance you can modify, call .copyInto(s3). See SetView for these methods.