TreeSet

Remove all elements from TreeSet example

With this example we are going to demonstrate how to remove all elements from a TreeSet. The TreeSet API provides methods for clearing a set and checking if it is empty. In short, to remove all elements from a TreeSet you should:

  • Create a new TreeSet.
  • Populate the set with elements, with add(E e) API method of TreeSet.
  • Invoke clear(), or removeAll(Collection c) API methods to remove all elements from the TreeSet.
  • Invoke the isEmpty() API method of TreeSet to check if the set has any elements. It returns true if the set is empty.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.TreeSet;
 
public class RemoveAllElementsTreeSet {
 
  public static void main(String[] args) {
 
    // Create a TreeSet and populate it with elements
    TreeSet treeSet = new TreeSet();
    treeSet.add("element_1");
    treeSet.add("element_2");
    treeSet.add("element_3");
 
    // boolean isEmpty() method checks whether TreeSet contains any elements or not   
    System.out.println("TreeSet empty : " + treeSet.isEmpty());
 
    // Remove all element from the TreeSet using clear() or removeAll() methods
    treeSet.clear();
    System.out.println("TreeSet empty : " + treeSet.isEmpty());

  }
}

Output:

TreeSet empty : false
TreeSet empty : true

 
This was an example of how to remove all elements from a TreeSet in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button