Symmetric difference of two sets

What is a symmetric difference of two sets? It is a less common set-algebraic operation — the set of elements contained in either of two specified sets but not in both. The following code shows if you have two friend lists, a list of friends that is either yours or mine.


The setup data is also used in Union of two sets, Difference of two sets and Intersection of two sets.

Set<String> yourFriends = Sets.newHashSet(
        "Desiree Jagger",
        "Benedict Casteel",
        "Evon Saddler",
        "Toby Greenland",
        "Norine Caruana",
        "Felecia Houghton",
        "Lanelle Franzoni",
        "Armandina Everitt",
        "Inger Honea",
        "Autumn Hendriks");

Set<String> myFriends = Sets.newHashSet(
        "Karrie Rutan",
        "Desiree Jagger",
        "Armandina Everitt",
        "Arlen Nowacki",
        "Ward Siciliano",
        "Mira Yonts",
        "Marcelo Arab",
        "Autumn Hendriks",
        "Mazie Hemstreet",
        "Toby Greenland");

Straight up Java

This snippet will find the difference between two collections specifically two sets using core JDK. We will first combine or add both sets together into yourFriendsOrMyFriends set. Then we will create temporary Set which we will call the retainAll and removeAll which will give us the difference of the two sets.

public void symmetric_set_difference_java () {

    Set<String> yourFriendsOrMyFriends = new HashSet<String>(yourFriends);
    yourFriendsOrMyFriends.addAll(myFriends);; //16;

    Set<String> tmp = new HashSet<String>(yourFriends);

    assertEquals(12, yourFriendsOrMyFriends.size());

Google Guava

This snippet will find the difference between two sets using Guava Set Utility. Sets.symmetricDifference will return a set that contains all elements in either set1 or set2 but not in both.

public void symmetric_set_difference_guava () {
    Set<String> yourFriendsOrMyFriends = Sets.symmetricDifference(yourFriends, myFriends);

    assertEquals(12, yourFriendsOrMyFriends.size());

Apache Commons

Using apache commons we will find the difference between sets. The CollectionUtils.disjunction will return a Collection containing the exclusive disjunction (symmetric difference) of the given Collections.

public void symmetric_set_difference_apache_commons () {

    Collection yourFriendsOrMyFriends = CollectionUtils.disjunction(yourFriends, myFriends);

    assertEquals(12, yourFriendsOrMyFriends.size());