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.

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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, "Amit");
        map.put(5, "Rahul");
        map.put(2, "Jai");
        map.put(6, "Amit");
        
          // using the method
        System.out.println("Size of the map is : "
                           + map.size());
    }
}

chevron_right


Output:

Size of the map is : 4

Example 2: For Generic Input

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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, "one");
        map.put(2, "two");
        map.put(3, "three");
        map.put(4, "four");
            
        // using the method
        System.out.println("Size of map is :"
                           + map.size());
    }
}

chevron_right


Output:

Size of the map is : 4

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.