Java Map size() Method Tutorial

In this section, we will learn what the Map size() method is and how to use it in Java.

What is Java Map size() Method?

The Java Map size() method is used to get the current number of entries (pair of keys and values) in a Map object.

Java size() Method Syntax:

int size()

size() Method Parameters:

The method does not take an argument.

size() Method Return Value:

The return value of this method is of type integer and is equal to the current number of entries in the target map object.

size() Method Exceptions:

The method does not throw an exception.

Example: using Map size() method

import java.util.Map; 
import java.util.HashMap;
class Main{
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("Omid","Dehghan");
        map.put("Jack","Bauer");
        map.put("Barack","Obama");
        map.put("Elon","Musk");
        map.put("Lex","Fridman");

        System.out.println(map.size());
    }
}

Output:

5

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies