Write a Java program to Remove HashSet elements contained in other HashSet


The code you provided demonstrates the usage of HashSet in Java to remove elements from one set that are present in another set. Here's a breakdown of how the code works:

  • The code starts by importing the necessary packages, including java.util.HashSet, which provides the HashSet class for creating and manipulating hash sets.
  • The Remove_OtherHashSet class is defined. Inside the main method, three instances of HashSet are created: n1, n2, and n3.
  • Elements are added to the hash sets using the add method. n1 contains elements 10, 20, 30, 40, 50, and 60. n2 contains elements 10, 20, 30, and 40. n3 contains elements 100, 200, 300, and 400.
  • The removeAll method is called on n1 with n2 as the argument. This method removes all elements from n1 that are also present in n2. If any elements are removed, it returns true; otherwise, it returns false. The code checks the return value and prints a corresponding message.
  • Similarly, the removeAll method is called on n1 with n3 as the argument. It removes elements from n1 that are present in n3 and prints a message based on the return value.
  • Finally, the contents of all three hash sets are printed using the System.out.println statements.

If you run this code, it will output the results of the removal operations and display the remaining elements in n1, n2, and n3.

Source Code

import java.util.*;
public class Remove_OtherHashSet
{
	public static void main(String[] args)
	{
		HashSet <Integer> n1 = new HashSet<Integer>();
		n1.add(10);
		n1.add(20);
		n1.add(30);
		n1.add(40);
		n1.add(50);
		n1.add(60);
 
		HashSet < Integer > n2 = new HashSet<Integer>();
		n2.add(10);
		n2.add(20);
		n2.add(30);
		n2.add(40);
 
		HashSet < Integer > n3 = new HashSet<Integer>();
		n3.add(100);
		n3.add(200);
		n3.add(300);
		n3.add(400);
 
		if (n1.removeAll(n2))
		{			
			System.out.println("Removed Items of HashSet2 contained in HashSet1.");
		}
		else
		{
			System.out.println("Unable to Remove Items from HashSet1.");
		}
 
		if (n1.removeAll(n3))
		{
			System.out.println("Removed Items of HashSet3 contained in HashSet1.");
		}
		else
		{
			System.out.println("Unable to Remove Items from HashSet1.");
		}
 
		System.out.println("HashSet 1 : " + n1);
		System.out.println("HashSet 2 : " + n2);
		System.out.println("HashSet 3 : " + n3);
	}
}

Output

Removed Items of HashSet2 contained in HashSet1.
Unable to Remove Items from HashSet1.
HashSet 1 : [50, 60]
HashSet 2 : [20, 40, 10, 30]
HashSet 3 : [400, 100, 200, 300]

Example Programs