Write a Java program to remove all of the elements from a hash set


This Java program demonstrates the removal of all elements from a HashSet. It creates a HashSet named col_set and adds seven strings to it using the add() method. Then, it prints out the initial contents of the HashSet using System.out.println().

After that, it calls the clear() method on the col_set HashSet, which removes all elements from it. Finally, it prints out the updated contents of the HashSet after clearing it.

The first line shows the initial contents of the HashSet before removing elements, and the second line shows an empty HashSet after calling the clear() method.

Source Code

import java.util.*;
public class Remove_AllElement
{
	public static void main(String[] args)
	{
		HashSet<String> col_set = new HashSet<String>();
		col_set.add("Red");
		col_set.add("Blue");
		col_set.add("Green");
		col_set.add("Pink");
		col_set.add("Black");
		col_set.add("Orange");
		col_set.add("White");
		System.out.println("Given HashSet : "+ col_set);		 
		col_set.clear();
		System.out.println("Removes all the Elements in HashSet : "+col_set);
	}
}

Output

Given HashSet : [Red, Pink, White, Blue, Black, Orange, Green]
Removes all the Elements in HashSet : []

Example Programs