Remove all elements from a HashSet in Java


To remove all the elements from HashSet, use the clear() method.

Create a HashSet and initialize elements −

String strArr[] = { "P", "Q", "R", "S" };
Set s = new HashSet(Arrays.asList(strArr));

Now, to remove all the above elements −

s.clear()

The following is an example to remove all elements from a HashSet −

Example

 Live Demo

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo {
   public static void main(String[] a) {
      String strArr[] = { "P", "Q", "R", "S" };
      Set s = new HashSet(Arrays.asList(strArr));
      strArr = new String[] { "R", "S", "T", "U" };
      s.addAll(Arrays.asList(strArr));
      System.out.println("Elements = " +s);
      // removing all elements
      s.clear();
      System.out.println("Set after removing all the elements = " +s);
   }
}

Output

Elements = [P, Q, R, S, T, U]
Set after removing all the elements = []

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 25-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements