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.


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.

public void union_of_sets_java () {
    Set<String> totalFriends = new HashSet<String>(yourFriends);
    assertEquals(16, totalFriends.size());

Google Guava

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

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.

public void union_of_sets_apache () {
    Collection<String> totalFriends = CollectionUtils.union(yourFriends, myFriends);
    assertEquals(16, totalFriends.size());