Get Size of HashMap Example in Java

In this example, we will see how to get the size of HashMap using size() method of HashMap class.

According to Oracle docs, size() method returns the number of key-value mappings present in the map.

Read Also  :  Check if a Particular Value exists in HashMap

Syntax of the size() method is as follows:

 public int size()

Parameters:

size() method does not take any parameters.

Returns:

size() method returns the size of the map, in other words, the number of key-value pairs present in the map.

Get Size of HashMap Example

1. HashMap with Integer keys and String values


 import java.util.*;

public class HashMapSizeExample {
    public static void main(String args[]) {
      
      // Creating HashMap object with Integer keys and String values    
      HashMap<Integer,String> map = new HashMap<>();
      
      // Adding elements to the HashMap object
      map.put(1, "CocoCola");
      map.put(2, "Pepsi");
      map.put(3, "Thums Up");
      map.put(4, "Fanta");
      
      // Calculating the size of the HashMap using size() method
      System.out.println(" Size of the given HashMap is: "+ map.size());
    }
}

Output:
Size of the given HashMap is: 4

Explanation


size() method returns 4 ,since we have 4 key-value mappings in HashMap. In the above example we showed the Integer keys and String values , however if you want the String keys and String values then you can change the syntax as follows :

 HashMap<String,String> map =  new HashMap<>();

2. HashMap with String keys and Integer values


 import java.util.*;

public class HashMapSizeExample2 {
    public static void main(String args[]) {
      
      // Creating HashMap object with String keys and Integer values    
      HashMap<String, Integer> map2 = new HashMap<>();
      
      // Putting elements to the HashMap object
      map2.put("Java", 10);
      map2.put("Hungry", 20);
      map2.put("Blog", 30);
      
      // Finding the size of the HashMap using size() method
      System.out.println(" Size of the given HashMap is: "+ map2.size());
    }
}

Output:
Size of the given HashMap is: 3

Explanation


We have 3 key-value pairs in HashMap, that's why size() method returns 3. In the above example, we calculated the size of the HashMap with String keys and Integer values.

That's all for today. Please mention in the comments if you have any questions related to how to get size of HashMap with examples in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry