JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

how to get java collection Map size() Method in Java With Examples

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

.