Skip to content

How to Check If TreeMap is Empty in Java Example

This example shows how to check if the TreeMap is empty in Java using the size method and isEmpty method of the TreeMap class. The example also shows the best method to check.

How to check if the TreeMap is empty in Java?

There are a couple of ways using which you can check if the TreeMap is empty as given below.

1. Using the isEmpty method

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

The isEmpty method returns false if there is at least one key-value mapping in the TreeMap object. The return type of the isEmpty method is boolean indicating whether there are any mappings in the map objects.

Output

2. Using the size method

You can use the size method of the TreeMap class and compare the size with 0 to determine whether the map is empty or not as given below.

Output

What is the preferred way to check?

There is not much difference between the isEmpty method and size method as far as the performance is concerned as both of them use the same internal variable size.

However, the preferred way to check if the TreeMap is empty is using the isEmpty method because it is more readable and clearly states the purpose of the code as compared to using the size method and comparing it with the 0.

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

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

References:
Java 8 TreeMap

About the author

Leave a Reply

Your email address will not be published.