Java Program to Check if the TreeMap is Empty
Last Updated :
07 Sep, 2021
The TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
Approaches:
- Using the isEmpty() method
- Using the size() method
Method 1: Using the isEmpty() method
The java.util.TreeMap.isEmpty() method of TreeMap class is used to check for the emptiness of the TreeMap.
Syntax :
TreeMap.isEmpty()
Parameters: The method does not take any parameters.
Return Value: The method returns boolean true if the TreeMap is empty else false. So, it will return false if there is at least one key-value mapping in the TreeMap object else True.
Example:
Java
import java.util.TreeMap;
public class GFG {
public static void main(String[] args)
{
TreeMap<Integer, String> tmap
= new TreeMap<Integer, String>();
boolean isEmpty = tmap.isEmpty();
System.out.println( "Is tmap empty : " + isEmpty);
tmap.put( 1 , "Geeks" );
tmap.put( 2 , "For" );
tmap.put( 3 , "skeeG" );
System.out.println( "The Mappings are: " + tmap);
isEmpty = tmap.isEmpty();
System.out.println( "Is tmap empty : " + isEmpty);
}
}
|
Output
Is tmap empty : true
The Mappings are: {1=One, 2=Two}
Is tmap empty : false
Method 2 : Using the size() method
The java.util.TreeMap.size() method of TreeMap class is used to check for the emptiness of the TreeMap by comparing the size with 0. The method returns True if TreeMap is empty else false.
Syntax :
(TreeMap.size() == 0) ;
Parameters: The method does not take any parameters.
Return Value: The method returns boolean True if the TreeMap is empty else false.
Example:
Java
import java.util.TreeMap;
public class GFG {
public static void main(String[] args)
{
TreeMap<Integer, String> tmap
= new TreeMap<Integer, String>();
System.out.println( "Is map empty : "
+ (tmap.size() == 0 ));
tmap.put( 1 , "One" );
tmap.put( 2 , "Two" );
System.out.println( "The Mappings are: " + tmap);
System.out.println( "Is map empty : "
+ (tmap.size() == 0 ));
}
}
|
Output
Is map empty : true
The Mappings are: {1=One, 2=Two}
Is map empty : false
Note: The same operation can be performed with any type of Mappings with variation and a combination of different data types.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...