Java HashMap isEmpty()

The syntax of the isEmpty() method is:

hashmap.isEmpty()

Here, hashmap is an object of the HashMap class.


isEmpty() Parameters

The isEmpty() method does not take any parameters.


isEmpty() Return Value

  • returns true if the hashmap does not contain any key/value mappings
  • returns false if the hashmap contains key/value mappings

Example: Check if HashMap is Empty

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // create an HashMap
        HashMap<String, Integer> languages = new HashMap<>();
        System.out.println("Newly Created HashMap: " + languages);

        // checks if the HashMap has any element
        boolean result = languages.isEmpty(); // true
        System.out.println("Is the HashMap empty? " + result);

        // insert some elements to the HashMap
        languages.put("Python", 1);
        languages.put("Java", 14);
        System.out.println("Updated HashMap: " + languages);

        // checks if the HashMap is empty
        result = languages.isEmpty();  // false
        System.out.println("Is the HashMap empty? " + result);
    }
}

Output

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

In the above example, we have created a hashmap named languages. Here, we have used the isEmpty() method to check whether the hashmap contains any elements or not.

Initially, the newly created hashmap does not contain any element. Hence, isEmpty() returns true. However, after we add some elements (Python, Java), the method returns false.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges