The set difference of a1 minus a2 is the set containing all of the elements found in a1 but not in a2. This example will find the difference between two sets returning a set that contains all elements contained by set1 and not contained by set2 using java, guava, and apache commons. Each snippet will find "possible friend requests to send".

Setup The setup data is also used in Union 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 In this snippet we will call java Set.removeAll which removes all elements contained in the specified collection.

@Test
public void difference_of_sets_java ( ) {
Set < String > possibleFriendRequests = new HashSet < String >( yourFriends );
possibleFriendRequests . removeAll ( myFriends );
assertEquals ( 6 , possibleFriendRequests . size ());
}

Google Guava Using guava Sets collection utility we will call Sets.difference which will return the difference of the specified sets.

@Test
public void difference_of_sets_guava ( ) {
Set < String > possibleFriendRequests = Sets . difference ( yourFriends , myFriends );
assertEquals ( 6 , possibleFriendRequests . size ());
}

Apache Commons Apache commons CollectionUtils.subtract will return a collection containing yourFriends - myFriends.

@Test
public void difference_of_sets_apache ( ) {
@SuppressWarnings ( "rawtypes" )
Collection possibleFriendRequests = CollectionUtils . subtract ( yourFriends , myFriends );
assertEquals ( 6 , possibleFriendRequests . size ());
}

Difference of two sets posted by Justin Musgrove on 18 November 2013

Tagged: java and java-collections

Share on: Facebook Google+

All the code on this page is available on github:

DifferenceOfTwoSets.java