A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/hashmap-size-method-in-java/ below:

Java HashMap size() Method - GeeksforGeeks

Java HashMap size() Method

Last Updated : 11 Jul, 2025

The size() method of the Java HashMap class is used to retrieve the number of key-value pairs currently stored in the HashMap.

Example 1: This example demonstrates the use of the size() method to get the number of elements in the HashMap.

Java
// Java program to demonstrates the working of size()
import java.util.HashMap;

public class Geeks {
    public static void main(String[] args)
    {
        // Creating a HashMap
        HashMap<String, Integer> hm = new HashMap<>();

        // Adding elements to the HashMap
        hm.put("Java", 10);
        hm.put("C++", 20);
        hm.put("python", 30);

        System.out.println("Size of the HashMap: "
                           + hm.size());
    }
}

Output
Size of the HashMap: 3
Syntax of HashMap size() Method

public int size()

Return Type: It returns an int value representing the number of key-value mapping in the HashMap.

Example 2: This example demonstrates the size of the HashMap after removing an element.

Java
// Java program to demomnstrates the use 
// of size() to track the number of entries 
// in the HashMap
import java.util.HashMap;

public class Geeks {
    public static void main(String[] args)
    {
        // Creating a HashMap
        HashMap<String, Integer> hm = new HashMap<>();

        // Adding elements to the HashMap
        hm.put("Java", 10);
        hm.put("C++", 20);
        hm.put("Python", 30);
        hm.put("JavaScript", 40);
      
        System.out.println("Size of the HashMap: "
                           + hm.size());
      
        // Removing an element
        hm.remove("Python");
      
        // Displaying the size of the 
        // HashMap after removal
        System.out.println(
            "Size of the HashMap After removal: "
            + hm.size());
    }
}

Output
Size of the HashMap: 4
Size of the HashMap After removal: 3


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4