How to intersect two sets in Java using java.util.Set data structure.

Set Intersection

Set is a collection that holds non-duplicate data. Set itself is an interface and has several implementing classes. Here are some know implementation of Set.

  • AbstractSet
  • ConcurrentSkipListSet
  • CopyOnWriteArraySet
  • EnumSet
  • HashSet
  • JobStateReasons
  • LinkedHashSet
  • TreeSet

In the example below, I have used HashSet to create two different sets. One set contains the name of all the developers of a fictitious team. Another set contains names of all the tech leads for that team. We are intersted to know what all tech leads are also developers. This can be done by doing an intersection of two sets. Intersection of sets can be done by calling retainAll() method as show below.

package com.icodejava.blog.datastructure;

import java.util.HashSet;
import java.util.Set;

/**
 * @author Kushal Paudyal
 * www.icodejava.com
 * 
 * Created on: 02/19/2014
 * Last Modified On: 02/19/2014
 *
 */
public class SetIntersection {
	
	public static void main(String args [] ) {
		/**
		 * Prepare a set of Developers
		 */
		Set<String> developers = new HashSet<String>();
		developers.add("Kushal");
		developers.add("Madan");
		developers.add("Pradip");
		developers.add("Nick");
		
		System.out.println("Developers: " + developers.toString());
		
		/**
		 * Prepare a set of Tech Leads
		 * Note that some of the items added are duplicates.
		 * Set does not allow duplicates which is apparent console print.
		 */
		Set<String> techLeads = new HashSet<String>();
		techLeads.add("Kushal");
		techLeads.add("Kushal"); //set does not allow duplicates
		techLeads.add("Nick");
		techLeads.add("Matthew");
		
		System.out.println("Tech Leads: " + techLeads.toString());
		
		/**
		 * To do set intersection, you can call retainAll() method
		 * and pass another set as parameter.
		 */
		developers.retainAll(techLeads);
		
		System.out.println("Tech Leads who are also developers:" + developers);
		
	}

}

Here is the output of this program:

Developers: [Kushal, Pradip, Madan, Nick]
Tech Leads: [Kushal, Matthew, Nick]
Tech Leads who are also developers:[Kushal, Nick]