Java HashMap size() Method
Last Updated :
20 Jan, 2025
Improve
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 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 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