Skip to content

Check If TreeSet is Empty in Java Example

This example shows how to check if TreeSet is empty in Java. This example also shows how to check if the TreeSet object is empty using isEmpty and size methods.

How to check if TreeSet is empty in Java?

The TreeSet is called empty if there are no elements in the set object. There are a couple of ways to check that as given below.

1. Using the TreeSet isEmpty method

The isEmpty method of the TreeSet class returns true if the TreeSet object is empty.

The isEmpty method returns a boolean value indicating whether there are any elements in the set object. It returns true if there are no elements present in the set object, false if there is at least one element present in the TreeSet object.

Output

2. Using the size method

We can also use the size method to check the same. The size method returns the number of elements stored in the TreeSet object.

We can compare the return value of the size method with 0 to check if the set object is empty or not as given below.

Output

Please visit the how to check the TreeSet size example to know more.

Which method should I use to check?

The TreeSet class internally maintains an instance of a NavigableMap to store the elements. Both the size method and isEmpty method calls the size method and isEmpty method of this map instance respectively.

The size and isEmpty methods of the map use the same size reference, so the performance should be the same for both of these methods.

However, when it comes to the readability of the code, the isEmpty method is more readable and shows the clear intent of the code as compared to using the size method for this purpose. That is why using the isEmpty method is the preferred way to check if the TreeSet is empty or not.

This example is a part of the Java TreeSet Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.