Write a Java program to empty an hash set


In the program, a HashSet named h_set is created and populated with some elements: "Blue", "Green", "Black", "Orange", "White", "Pink", and "Yellow". The program then removes all elements from h_set by calling the removeAll() method on h_set itself. This method removes all elements from the HashSet. Finally, the program prints the contents of h_set after the removal operation.

The output shows the initial contents of h_set, followed by the contents of h_set after removing all elements. As you can see, h_set is now an empty HashSet.

Source Code

import java.util.*;
public class Empty_HashSet
{
	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);		
		h_set.removeAll(h_set); // Remove all elements
		System.out.println("HashSet After Removing all the Elements : "+h_set);   
	}
}

Output

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

Example Programs