Intersection of Sets in Java

      No Comments on Intersection of Sets in Java




Set is an interface which extends Collection Interface. Set does not maintain the order of objects inserted and hence it is an unordered collection of objects. Also, It can not store duplicate values.

What is Intersection of Sets in JAVA?

Intersection of Sets in Java implies the elements / objects which are common to two different sets.
e.g.

Set<Integer> s = new HashSet<Integer>();
s.add(123);
s.add(23);
s.add(98);
s.add(100);

Set<Integer> s1 = new HashSet<Integer>();
s1.add(12);
s1.add(235);
s1.add(98);
s1.add(150);

Here, in the above two sets only common element is 98.

How to find Intersection of Set in JAVA?

Set has a method retainAll() which finds the intersection of two sets. retainAll() method finds the common elements / objects.

Syntax of retainAll() Method:

boolean java.util.Set.retainAll(Collection c)

Retains only the elements in this set that are contained in the specified collection .

Demo Program to Find Intersection of Set in JAVA:

package com.masterjavatutorial;

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

public class TestExample {
	public static void main(String[] args){
		Set s = new HashSet();
		s.add(12);
		s.add(23);
		s.add(98);
		s.add(100);

		Set s1 = new HashSet();
		s1.add(12);
		s1.add(235);
		s1.add(98);
		s1.add(150);
		
		s.retainAll(s1); 
		System.out.println(s); 
 	}
			
}

Output of the above program is as below:

[98, 12]