Java HashMap size() Method

Java HashMap Java HashMap

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

The syntax of the size() method is:

hashmap.size()

Note:hashmap is an object of the HashMap class.

Parameter Description:

  • None

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<Integer, String> sites = new HashMap<>();

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

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

Executing the above program outputs the result:

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

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

Java HashMap Java HashMap

Other Extensions