Java Map isEmpty() Method Tutorial

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

What is Java Map isEmpty() Method?

The Java Map isEmpty() method is used to see if a Map object is empty (meaning there’s no entry at all in that object).

Java isEmpty() Method Syntax:

boolean isEmpty()

isEmpty() Method Parameters:

The method does not take an argument.

isEmpty() Method Return Value:

The return value of this method is of type boolean and is equal to true if the target Map object was in fact empty! Otherwise, the value false will return (meaning there’s at least one element in that map object).

isEmpty() Method Exceptions:

The method does not throw an exception.

Example: using Map isEmpty() 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");

        if (!map.isEmpty()){
            map.forEach((k,v)->{
                System.out.println(k+" "+v);
            });
        }else{
            System.out.println("The target map object is empty!");
        }
    }
}

Output:

Elon Musk

Barack Obama

Omid Dehghan

Jack Bauer

Lex Fridman
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies