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
Related Articles
import java.util.*;
public class HashMapSizeExample {
public static void main(String args[]) {
// Creating a HashMap of int keys and String values
HashMapInteger, String> hashmap = new HashMapInteger, String>();
// Adding Key and Value pairs to HashMap
hashmap.put(11,"Apple");
hashmap.put(22,"Banana");
hashmap.put(33,"Mango");
hashmap.put(44,"Pear");
hashmap.put(55,"PineApple");
// int size() method returns the number of key value pairs
System.out.println("Size of HashMap : " + hashmap.size());
}
}
Output
Size of HashMap : 5size() 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 :
HashMapString,String> hashmap = new HashMapString,String>();
Please mention in comments if you have any questions.