How to get java collection Map size() Method in Java With Examples
Map size() method in Java is used to get the total number entries i.e, key-value pair. So this method is useful when you want total entries present on the map. If the map contains more than Integer.MAX_VALUE elements return Integer.MAX_VALUE.
Parameters: (This method does not take any parameters.)
Return value (This method returns the number of key-value mappings in this map.)
Syntax: int size();
Example 1: For non-generic input
// Java program to illustrate
// the Map size() Method
import java.util.*;
public class MapSizeExample {
// Main Method
public static void main(String[] args)
{
Map map = new HashMap();
// Adding key-values
map.put(1, "delhi");
map.put(5, "mumbai");
map.put(2, "noida");
map.put(6, "meerut");
// using the method
System.out.println("Size of the map is : "
+ map.size());
}
}
Output:Size of the map is : 4
Example 2: For Generic Input
// Java program to illustrate
// the Map size() Method
import java.util.*;
class MapSizeExample {
// Main Method
public static void main(String[] args)
{
Map<Integer, String> map
= new HashMap<Integer, String>();
map.put(1, "delhi");
map.put(2, "mumbai");
map.put(3, "noida");
map.put(4, "ghaziabad");
// using the method
System.out.println("Size of map is :"
+ map.size());
}
}
Output:Size of the map is : 4