This example shows how to get TreeMap size in Java using the size method. The size method returns the number of entries stored in the TreeMap object.
How to get TreeMap size using the size method in Java (TreeMap length)?
The size
method of the TreeMap class returns the number of entries stored in the TreeMap object.
1 |
public int size() |
The size
method returns an int value representing the number of key-value mappings stored in the TreeMap object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.util.TreeMap; public class TreeMapSizeExample { public static void main(String[] args) { //creates an empty TreeMap object TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); /* * To check the size of the TreeMap, use * the size method */ int size = treemap.size(); //this will print 0 as the TreeMap is empty System.out.println("Size is: " + size); //add key-value mappings treemap.put(10, "Ten"); treemap.put(11, "Eleven"); treemap.put(12, "Twelve"); size = treemap.size(); //this will print 3 as the TreeMap now contains 3 entries System.out.println("Size is: " + size); } } |
Output
1 2 |
Size is: 0 Size is: 3 |
How to check if TreeMap is empty using the size method?
We can get the size of the TreeMap using the size
method and compare the return value with 0 to check if the TreeMap is empty or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.TreeMap; public class TreeMapSizeExample { public static void main(String[] args) { //creates an empty TreeMap object TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); //this will print true as the TreeMap is empty System.out.println("Is empty: " + (treemap.size() == 0)); //add key-value mappings treemap.put(10, "Ten"); treemap.put(11, "Eleven"); treemap.put(12, "Twelve"); //this will false as the TreeMap contains 3 entries System.out.println("Is empty: " + (treemap.size() == 0)); } } |
Output
1 2 |
Is empty: true Is empty: false |
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