Remove all elements from TreeSet in Java

Java 8Object Oriented ProgrammingProgramming

Use the clear() method to remove all elements from TreeSet.

First, create a TreeSet and add elements −

TreeSet<String> set = new TreeSet<String>();
set.add("65");
set.add("45");
set.add("19");
set.add("27");
set.add("89");
set.add("57");

Now, remove all the elements −

set.clear();

The following is an example to remove all elements from TreeSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> set = new TreeSet<String>();
      set.add("65");
      set.add("45");
      set.add("19");
      set.add("27");
      set.add("89");
      set.add("57");
      System.out.println("TreeSet elements...");
      Iterator<String> i = set.iterator();
      while(i.hasNext()) {
         System.out.println(i.next());
      }
      set.clear();
      System.out.println("Updated TreeSet elements...");
      System.out.println(set);
   }
}

Output

TreeSet elements...
19
27
45
57
65
89
Updated TreeSet elements...
[]
raja
Published on 11-Jan-2019 11:27:54
Advertisements