English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/O)

Java Reader/Writer

Java other topics

Usage and example of Java HashMap isEmpty()

Java HashMap Methods

The Java HashMap isEmpty() method checks if the hash map is empty.

The syntax of isEmpty() method is:

hashmap.isEmpty()

isEmpty() parameters

isEmpty() method without any parameters.

The return value of isEmpty()

  • If the hash map does not contain anyKey/ValueIf the mapping is present, return true

  • If the hash map containsKey/ValueIf the mapping is not present, return false

Example: Check if the HashMap is empty

import java.util.HashMap;
class Main {
    public static void main(String[] args) {
        //Create HashMap
        HashMap<String, Integer> languages = new HashMap<>();
        System.out.println("The newly created HashMap: " + languages);
        //Check if the HashMap contains any elements
        boolean result = languages.isEmpty(); // true
        System.out.println("Is HashMap empty? ", + result);
        //Insert some elements into the HashMap
        languages.put("Python", 1);
        languages.put("Java", 14);
        System.out.println("Updated HashMap: ", + languages);
        //Check if HashMap is Empty
        result = languages.isEmpty();  // false
        System.out.println("Is HashMap empty? ", + result);
    }
}

Output Result

Newly created HashMap: {}
Is HashMap empty? true
Updated HashMap: {Java=14, Python =1}
Is HashMap empty? false

In the above example, we created a hash map named languages. Here, we used the isEmpty() method to check if the hash map contains any elements.

Initially, the newly created hash map does not contain any elements. Therefore, isEmpty() returns true. However, after adding some elements (Python,JavaAfter that, the method returns false.

Java HashMap Methods