This example demonstrates how to remove all elements contained in Java TreeSet (clear TreeSet object with clear or removeAll methods). We will also show you how to check whether TreeSet object is empty with isEmpty method.
Source Code
package com.beginner.examples;
import java.util.TreeSet;
public class RemoveAllElementsFromTreeSet {
public static void main(String[] args) {
//create TreeSet.
TreeSet treeSet = new TreeSet();
treeSet.add("A");
treeSet.add("B");
treeSet.add("C");
treeSet.add("D");
System.out.println("Before removal , treeSet contains : " + treeSet);
/*
* To remove all elements from Java TreeSet or to clear TreeSet use clear() method.
*/
treeSet.clear();
System.out.println("After removal , treeSet contains : " + treeSet);
}
}
Output:
Before removal , treeSet contains : [A, B, C, D]
After removal , treeSet contains : []
References
Imported packages in Java documentation: