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.
1 |
public boolean isEmpty() |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.TreeMap; public class CheckIfTreeMapIsEmptyExample { public static void main(String[] args) { //creates an empty TreeMap object TreeMap<Integer, String> tmapColors = new TreeMap<Integer, String>(); //this will return true as the map is empty boolean isEmpty = tmapColors.isEmpty(); System.out.println("Is map empty? " + isEmpty); //add some mappings tmapColors.put(1, "Red"); tmapColors.put(2, "Green"); //this will return false as the map is not empty isEmpty = tmapColors.isEmpty(); System.out.println("Is map empty? " + isEmpty); } } |
Output
1 2 |
Is map empty? true Is map empty? false |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.TreeMap; public class CheckIfTreeMapIsEmptyExample { public static void main(String[] args) { //an empty TreeMap object TreeMap<Integer, String> tmapColors = new TreeMap<Integer, String>(); //this will return true as the map is empty System.out.println("Is map empty? " + (tmapColors.size() == 0)); //add some mappings tmapColors.put(1, "Red"); tmapColors.put(2, "Green"); //this will return false as the map is not empty System.out.println("Is map empty? " + (tmapColors.size() == 0)); } } |
Output
1 2 |
Is map empty? true Is map empty? false |
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