Home » Core Java » util » TreeSet » Remove all elements from TreeSet example

About Ilias Tsagklis

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

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments