Remove all elements from a HashSet in Java

Java 8Object Oriented ProgrammingProgramming

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 = []
raja
Published on 10-Jan-2019 09:31:07
Advertisements