Intersection of two sets

This example will show how to find the intersection of two sets using java, guava and apache commons. The intersection of two sets is the set containing only the elements common to both sets.

Setup

The setup data is also used in Union of two sets, Difference 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 will show how to find common elements in two sets using java. The Set.retainAll method will retain only the elements from the set that are in the passed in collection. Another way to say it is, it will remove all the elements from the set not contained in the collection.

@Test
public void intersection_of_sets_java () {

    Set<String> mutalFriends = new HashSet<String>(yourFriends);
    mutalFriends.retainAll(myFriends);

    assertEquals(4, mutalFriends.size());
}

Google Guava

Guava Sets utility class contains a Sets.intersection which will find the intersection of two sets. The returned set will contain all elements contained in both sets.

@Test
public void intersection_of_sets_guava () {

    Set<String> mutalFriends = Sets.intersection(yourFriends, myFriends);

    assertEquals(4, mutalFriends.size());
}

Apache Commons

This snippet will demonstrate how to find the intersection of two lists using apache commons. The returned collection will contain elements that are in both sets.

@Test
public void intersection_of_sets_apache_commons () {

    @SuppressWarnings("rawtypes")
    Collection mutalFriends = CollectionUtils.intersection(yourFriends, myFriends);

    assertEquals(4, mutalFriends.size());
}