How to check if a HashMap is empty or not?

In this post, I will be sharing how to check if HashMap is empty or not. There are two ways to perform this check:

1. isEmpty() method [Recommended]

2. size() method

Read Also :  Convert Collection To List in Java

Let's dive deep into the topic:

How to check if HashMap is empty or not?

1. Using isEmpty() method


According to Oracle docs, this method returns true if the map contains no key-value mappings.

Parameters:

isEmpty() method does not take any parameters.

Returns:

isEmpty() method returns true if the map contains no key-value mappings.

Syntax:


 public boolean isEmpty()


Program for How to Check if a HashMap is Empty or Not



 import java.util.HashMap;

public class HashMapEmptyExample {
    public static void main(String args[]) {
      
      // Creating HashMap object with Integer keys and String values    
      HashMap<Integer, String> map = new HashMap<>();
      
      // Checking whether HashMap is empty or not
      System.out.println("Checking Is HashMap empty?: " + map.isEmpty());
      
      // Adding elements to the HashMap object
      map.put(100, "Jack");
      map.put(200, "John");
      map.put(300, "Smith");
      
      // Checking again whether HashMap is empty or not
      System.out.println("Checking Is HashMap empty?: "+ map.isEmpty());
    }
}


Output:
Checking Is HashMap empty?: true
Checking Is HashMap empty?: false

2. Using size() method


I have already explained the size() method here. We can easily check if HashMap is empty or not by using size() method. If size() method returns 0 then the HashMap is empty otherwise not.

 import java.util.*;

public class HashMapEmptyExample2 {
    public static void main(String args[]) {
      
      // Creating HashMap object with String keys and String values    
      HashMap<String, String> map = new HashMap<>();
      
      // Checking whether HashMap is empty or not using size() method
      System.out.println("Checking Is HashMap empty using size() method?: " + (map.size()==0));
      
      // Putting elements to the HashMap object
      map.put("100", "Java");
      map.put("1000", "Python");
      map.put("10000", "Javascript");
      
      // Checking again whether HashMap is empty or not using size() method
      System.out.println("Checking Is HashMap empty using size() method?: "+ (map.size()==0));
    }
}


Output:
Checking Is HashMap empty using size() method?: true
Checking Is HashMap empty using size() method?: false

Which one is better size() or isEmpty()?


I would prefer isEmpty() over size() method as it clearly states the purpose of the code.

That's all for today. Please mention in the comments if you have any questions related to how to check if a HashMap is empty or not.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry