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. Syntax of the method size() is as follows:

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

Read Also  :  Check if a Particular Value exists in HashMap

Get Size of HashMap Example

import java.util.*;

 public class HashMapSizeExample {
    public static void main(String args[]) {
    // Creating a HashMap of int keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
    // Adding Key and Value pairs to HashMap
    // int size() method returns the number of key value pairs 
    System.out.println("Size of HashMap : " + hashmap.size()); 


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

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

Please mention in comments if you have any questions.

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry