Java Utility Library

Java HashMap - isEmpty() Method



The java.util.HashMap.isEmpty() method is used to check whether the map is empty or not. It returns true if the map contains no key-value mappings, else returns false.

Syntax

public boolean isEmpty()

Parameters

No parameter is required.

Return Value

Returns true if the map contains no key-value mapping, else returns false.

Exception

NA

Example:

In the example below, the java.util.HashMap.isEmpty() method is used to check whether the map is empty or not.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a hash map
    HashMap<Integer, String> MyMap = new HashMap<Integer, String>();

    //checking for empty
    System.out.println("Is MyMap empty?: "+ MyMap.isEmpty());

    //populating hash map
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");
    MyMap.put(104, "Jo");

    //checking for empty
    System.out.println("Is MyMap empty?: "+ MyMap.isEmpty());
  }
}

The output of the above code will be:

Is MyMap empty?: true
Is MyMap empty?: false

❮ Java.util - HashMap