Java HashMap - size() Method
The java.util.HashMap.size() method returns the total number of key-value mapping present in the map.
Syntax
public int size()
Parameters
No parameter is required.
Return Value
Returns the total number of key-value mapping in the map.
Exception
NA
Example:
In the example below, the java.util.HashMap.size() method is used to find out the total number of key-value mapping in the map.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a hash map HashMap<Integer, String> MyMap = new HashMap<Integer, String>(); //populating hash map MyMap.put(101, "John"); MyMap.put(102, "Marry"); MyMap.put(103, "Kim"); MyMap.put(104, "Jo"); System.out.println("Size of MyMap: "+ MyMap.size()); //adding one more pair in the hash map MyMap.put(105, "Ramesh"); System.out.println("Size of MyMap: "+ MyMap.size()); } }
The output of the above code will be:
Size of MyMap: 4 Size of MyMap: 5
❮ Java.util - HashMap