Symmetric difference of two sets in Java

use retain all,remove all then addAll to do a union of existing set.

  1. intersectionSet.retainAll(set2) // intersectionSet is a copy of set1
  2. set1.addAll(set2); // do a union of set1 and set2
  3. then remove the duplicates set1.removeAll(intersectionSet);

You could use CollectionUtils#disjunction

EDIT:

Alternatively with less pre-Java-5-ness, use Guava Sets#symmetricDifference


You're after the symmetric difference. This is discussed in the Java tutorial.

Set<Type> symmetricDiff = new HashSet<Type>(set1);
symmetricDiff.addAll(set2);
// symmetricDiff now contains the union
Set<Type> tmp = new HashSet<Type>(set1);
tmp.retainAll(set2);
// tmp now contains the intersection
symmetricDiff.removeAll(tmp);
// union minus intersection equals symmetric-difference