Union of two sets

This example will demonstrate how to find the union of two sets using java, guava and apache commons. Unlike merging two lists where it will combine all items, the union of two sets is a set containing all of the elements contained in either set. The snippets below will show how to find unique friends between two sets that represents yourFriends and myFriends.

Setup

The setup data is also used in Difference of two sets, Intersection of two sets and Symmetric difference 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, using core functionality in the JDK, will add all the elements in the specified collection to the sets if they are not already present.

@Test
public void union_of_sets_java () {

    Set<String> totalFriends = new HashSet<String>(yourFriends);
    totalFriends.addAll(myFriends);

    assertEquals(16, totalFriends.size());
}

Google Guava

This snippet will find the unique elements in two sets using guava.

@Test
public void union_of_sets_guava () {

    Set<String> totalFriends = Sets.union(yourFriends, myFriends);

    assertEquals(16, totalFriends.size());
}

Apache Commons

This snippet will find the union of two collections using apache commons CollectionUtils.union method.

@Test
public void union_of_sets_apache () {

    @SuppressWarnings("unchecked")
    Collection<String> totalFriends = CollectionUtils.union(yourFriends, myFriends);

    assertEquals(16, totalFriends.size());
}