Java Utility Library

Java TreeMap - size() Method



The java.util.TreeMap.size() method returns the total number of key-value mapping present in the map.

Syntax

public int size()

Parameters

No parameter is required.

Return Value

Returns the total number of key-value mapping in the map.

Exception

NA

Example:

In the example below, the java.util.TreeMap.size() method is used to find out the total number of key-value mapping in the map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treemap
    TreeMap<Integer, String> MyMap = new TreeMap<Integer, String>();

    //populating the map
    MyMap.put(102, "John");
    MyMap.put(103, "Marry");
    MyMap.put(101, "Kim");
    MyMap.put(104, "Jo");

    System.out.println("Size of MyMap: "+ MyMap.size());    

    //adding one more pair in the map
    MyMap.put(105, "Ramesh"); 

    System.out.println("Size of MyMap: "+ MyMap.size());  
  }
}

The output of the above code will be:

Size of MyMap: 4
Size of MyMap: 5

❮ Java.util - TreeMap