What is size in Java HashMap?

Overview

The size function in HashMap is used to find the size of a HashMap. The size entails all of the key-value pairs in a HashMap. As HashMap is defined in the util package in Java, you must first import the util package before using the size function, as shown below:

import java.util.*;

The syntax for size is shown below:

hashmapName.size()

Parameters

The size function takes no mandatory parameters as input.

Return value

The size function returns the number of keys in a Hashmap.

Example

The example below will help you understand the size function better. First, we define the HashMap and add keys to it, using the put function. Then, we print out the size of the HashMap using the size function.

import java.util.*;
class HelloWorld {
public static void main( String args[] ) {
HashMap<String, Integer> hash = new HashMap<String, Integer>();
hash.put("Samia", 22);
hash.put("Sana", 21);
System.out.println("Size of Map: " + hash.size());
}
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved