Java Program to remove all elements from a set in Java

Java 8Object Oriented ProgrammingProgramming

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

Here is our set −

HashSet <String> set1 = new HashSet <String>();
set1.add("Mat");
set1.add("Sat");
set1.add("Cat");

Now, let us remove all the elements −

set1.clear();

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

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet <String> set1 = new HashSet <String>();
      set1.add("Mat");
      set1.add("Sat");
      set1.add("Cat");
      System.out.println("Set = "+ set1);
      set1.clear();
      System.out.println("Set after removing all the elements (blank) = "+ set1);
   }
}

Output

Set = [Mat, Sat, Cat]
Set after removing all the elements (blank) = []
raja
Published on 10-Jan-2019 13:57:25
Advertisements