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 returnInteger.MAX_VALUE
Syntax:
int size();
Parameter: This method does not take any parameter.
Return value: This method returns the number of key-value mappings in this map.
Example 1: For non-generic input
Java
import java.util.*;
public class MapSizeExample {
public static void main(String[] args)
{
Map map = new HashMap();
map.put( 1 , "Amit" );
map.put( 5 , "Rahul" );
map.put( 2 , "Jai" );
map.put( 6 , "Amit" );
System.out.println( "Size of the map is : "
+ map.size());
}
}
|
Output:
Size of the map is : 4
Example 2: For Generic Input
Java
import java.util.*;
class MapSizeExample {
public static void main(String[] args)
{
Map<Integer, String> map
= new HashMap<Integer, String>();
map.put( 1 , "one" );
map.put( 2 , "two" );
map.put( 3 , "three" );
map.put( 4 , "four" );
System.out.println( "Size of map is :"
+ map.size());
}
}
|
Output:
Size of the map is : 4