Search...
Tutorials
Practice J
Jobs
Tutorial Advanced Java Interview Questions Exercises Examples Quizzes Projects Cheatsheet DSA in Java Java Colle
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 program to demonstrates the working of size()
import [Link];
public class Geeks {
public static void main(String[] args)
{
// Creating a HashMap
HashMap<String, Integer> hm = new HashMap<>();
// Adding elements to the HashMap
[Link]("Java", 10);
[Link]("C++", 20);
[Link]("python", 30);
[Link]("Size of the HashMap: "
+ [Link]());
}
}
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 [Link];
public class Geeks {
public static void main(String[] args)
{
// Creating a HashMap
HashMap<String, Integer> hm = new HashMap<>();
// Adding elements to the HashMap
[Link]("Java", 10);
[Link]("C++", 20);
[Link]("Python", 30);
[Link]("JavaScript", 40);
[Link]("Size of the HashMap: "
+ [Link]());
// Removing an element
[Link]("Python");
// Displaying the size of the
// HashMap after removal
[Link](
"Size of the HashMap After removal: "
+ [Link]());
}
}
Output
Size of the HashMap: 4
Size of the HashMap After removal: 3
Comment C chinm… 2
Article Tags: Misc Java Java-Collections Java - util package +2 More
Company Explore Tutorials Courses Preparation
About Us POTD Programming ML and Data Corner
Corporate & Communications Address: Legal Practice Languages Science Interview
Privacy Problems DSA DSA and Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Policy Connect Web Placements Aptitude
Pradesh (201305) Careers Blogs Technology Web Puzzles
Contact Us Upskill AI, ML & Development GfG 160
Registered Address:
Corporate Courses Data Science Data Science System Design
K 061, Tower K, Gulshan Vivante Solution DevOps Programming
Apartment, Sector 137, Noida, Gautam
Campus CS Core Languages
Buddh Nagar, Uttar Pradesh, 201305
Training Subjects DevOps &
Program GATE Cloud
School GATE
Subjects