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.

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.

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.

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.