Write a Java program to compare two sets and retain elements which are same on both sets


In this program, two HashSet objects, set1 and set2, are created and populated with some elements. The elements in set1 are: "Red", "Pink", "Green", "Black", "White", and "Yellow". The elements in set2 are: "Yellow", "Purple", "Black", "Orange", and "Pink".

The retainAll() method is then called on set1 and passed set2 as an argument. This method modifies set1 to retain only the elements that are present in both sets, effectively finding the common elements. Finally, the contents of set1 are printed to the console.

Source Code

import java.util.*;
public class SameBothSets
{
	public static void main(String[] args)
	{
		HashSet<String> set1 = new HashSet<String>();
		set1.add("Red");
		set1.add("Pink");
		set1.add("Green");
		set1.add("Black");
		set1.add("White");
		set1.add("Yellow");
		System.out.println("Frist HashSet : "+set1);
		HashSet<String> set2 = new HashSet<String>();
		set2.add("Yellow");
		set2.add("Purple");
		set2.add("Black");
		set2.add("Orange");
		set2.add("Pink");
		System.out.println("Second HashSet : "+set2);
		set1.retainAll(set2);
		System.out.println("HashSet content : "+set1);
	}
}

Output

Frist HashSet : [Red, Pink, White, Yellow, Black, Green]
Second HashSet : [Pink, Yellow, Purple, Black, Orange]
HashSet content : [Pink, Yellow, Black]

Example Programs