Write a Java program to Removing elements of the hashset


The program starts with the import statement import java.util.HashSet; , which imports the HashSet class from the java.util package. Next, the program defines a public class called Removing_Elements. Within the Removing_Elements class, the main method is declared and serves as the entry point for the program. It takes an array of strings (args) as input.

Inside the main method, a new instance of the HashSet class is created using the constructor: HashSet h_set = new HashSet();. The specifies the type of elements that will be stored in the HashSet, which in this case is a string.

After that, several elements are added to the HashSet using the add() method. The elements added are "Blue", "Green", "Black", "Orange", "White", "Pink", and "Yellow". Next, the program prints the contents of the HashSet using the System.out.println() statement. It displays the message "Given HashSet: " followed by the elements contained in the HashSet.

The program then removes two elements from the HashSet using the remove() method. The elements being removed are "White" and "Green". Finally, the program prints the updated contents of the HashSet using another System.out.println() statement. It displays the message "Removing Elements HashSet: " followed by the remaining elements in the HashSet.

Source Code

import java.util.HashSet;
public class Removing_Elements
{
	public static void main(String args[])
	{
		HashSet <String> h_set= new HashSet <String>();
		h_set.add("Blue");
		h_set.add("Green");
		h_set.add("Black");
		h_set.add("Orange");
		h_set.add("White");
		h_set.add("Pink");
		h_set.add("Yellow");
		System.out.println("Given HashSet : " + h_set);
 
		//removing elements
		h_set.remove("White");
		h_set.remove("Green");
 
		System.out.println("Removing Elements HashSet : " + h_set);		
	}
}

Output

Given HashSet : [White, Pink, Blue, Yellow, Black, Orange, Green]
Removing Elements HashSet : [Pink, Blue, Yellow, Black, Orange]

Example Programs