Write a Java program to compare two hash sets


In the 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".

A loop is then used to iterate over each element in set1. For each element, the program checks if it is present in set2 using the contains() method. If the element is found in set2, the program prints "Yes". Otherwise, it prints "No". Finally, the program outputs the result of the comparison.

Source Code

import java.util.*;
public class Compare_TwoSets
{
	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);
		System.out.println("Compare Two Hashsets : ");
 
		HashSet<String> res = new HashSet<String>();
		for (String e : set1)
		{
			System.out.println(set2.contains(e) ? "Yes" : "No");
		}
	}
}

Output

Frist HashSet : [Red, Pink, White, Yellow, Black, Green]
Second HashSet : [Pink, Yellow, Purple, Black, Orange]
Compare Two Hashsets :
No
Yes
No
Yes
Yes
No

Example Programs