Easy Tutorial
❮ Collection Reverse Java Sending Email ❯

Java HashMap size() Method

The size() method is used to calculate the number of key/value pairs in a hashMap.

The syntax for the size() method is:

hashmap.size()

Note: hashmap is an object of the HashMap class.

Parameter Description:

Return Value

Returns the number of key/value pairs in the hashMap.

Example

The following example demonstrates the use of the size() method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {

        HashMap&lt;Integer, String> sites = new HashMap<>();

        // Adding some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        sites.put(3, "Taobao");
        System.out.println("HashMap: " + sites);

        // Getting the number of key/value mappings in the HashMap
        int size = sites.size();
        System.out.println("Size of HashMap: " + size);
    }
}

Executing the above program outputs:

HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Size of HashMap: 3

In the above example, we created a HashMap named sites and used the size() method to calculate the number of key/value pairs in sites.

❮ Collection Reverse Java Sending Email ❯