Easy Tutorial
❮ Thread Showall Number Ceil ❯

Java HashMap isEmpty() Method

Java HashMap

The isEmpty() method is used to check if the HashMap is empty.

The syntax for the isEmpty() method is:

hashmap.isEmpty()

Note: hashmap is an object of the HashMap class.

Parameter Description:

Return Value

Returns true if the HashMap contains no key-value mappings, otherwise returns false.

Example

The following example demonstrates the use of the isEmpty() method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {

        HashMap&lt;Integer, String> sites = new HashMap<>();
        // Check if the HashMap is empty
        boolean result = sites.isEmpty(); // true
        System.out.println("Is it empty? " + result);

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        sites.put(3, "Taobao");
        System.out.println("HashMap: " + sites);

        result = sites.isEmpty(); // false
        System.out.println("Is it empty? " + result);
    }
}

Executing the above program outputs:

Is it empty? true
HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Is it empty? false

In the above example, we created a HashMap named sites and used the isEmpty() method to check if it is empty.

Java HashMap

❮ Thread Showall Number Ceil ❯