What is the TreeSet.isEmpty() function in Java?

The TreeSet.isEmpty() method is present in the TreeSet class in the java.util package. It is used to check whether a TreeSet is empty or contains any elements in it.

Parameter

The TreeSet.isEmpty() method doesn’t take any parameters.

Return value

The method returns a Boolean value.

  • True: When the TreeSet is empty.
  • False: When the TreeSet is not empty.

Examples

Example 1

TreeSet = [1,8,5,3,9]

It contains some elements, i.e., the TreeSet is not empty.

So, the result of the TreeSet.isEmpty() method is false.

Example 2

TreeSet = [ ]

This one doesn’t contain any elements, i.e., the TreeSet is empty.

So, the result of the TreeSet.isEmpty() method is true.

Code

Let us look at the code snippet below.

import java.io.*;
import java.util.TreeSet;
class Main
{
public static void main(String args[])
{
TreeSet<Integer> tree_set = new TreeSet<Integer>();
tree_set.add(1);
tree_set.add(8);
tree_set.add(5);
tree_set.add(3);
tree_set.add(0);
System.out.println("TreeSet is empty? : " + tree_set.isEmpty());
tree_set.clear();
System.out.println("TreeSet is empty? : " + tree_set.isEmpty());
}
}

Explanation

  • In lines 1 and 2, we import the required packages and classes.

  • In line 4, we made a Main class.

  • In line 6, we made a main function.

  • In line 8, we declared a TreeSet of Integer type.

  • In lines 9 to 13, we add the elements into the TreeSet by using the TreeSet.add() method.

  • In lines 14 and 17, we display the result of whether the TreeSet is empty or not using TreeSet.isEmpty() method with a message.

  • In line 16, we removed all the elements from the TreeSet by using TreeSet.clear() method.

In this way, the TreeSet.isEmpty() method can be used to check whether the TreeSet is empty or not.

Free Resources