This example shows how to check if HashMap is empty in Java using the isEmpty method and size method. The example also shows which is the best way to check.
How to check if HashMap is empty in Java?
There are a couple of ways using which you can perform this check.
1. Check using the isEmpty method
You can use the isEmpty
method of the HashMap class to check if the HashMap is empty.
1 |
public boolean isEmpty() |
This method returns true if the HashMap contains no key-value mappings, false otherwise. The isEmpty
method does not take any parameters and returns a boolean value depending upon the number of mappings stored in the HashMap object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.HashMap; public class CheckIfHashMapIsEmptyExample { public static void main(String[] args) { //create new and empty HashMap HashMap<Integer, String> hMapNumbers = new HashMap<Integer, String>(); /* * This will return true as there are no * mappings in the HashMap object */ System.out.println("is empty? " + hMapNumbers.isEmpty() ); //add key-value pairs hMapNumbers.put(1, "One"); hMapNumbers.put(2, "Two"); hMapNumbers.put(2, "Three"); /* * This will return false as there are 3 * mappings in the HashMap object */ System.out.println("is empty? " + hMapNumbers.isEmpty() ); } } |
Output
1 2 |
is empty? true is empty? false |
2 Check using the size method
You can also use the size
method of the HashMap class to check if it is empty. Get the size of the HashMap and compare it with 0 to check if it is empty or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.HashMap; public class CheckIfHashMapIsEmptyExample { public static void main(String[] args) { //create new & empty HashMap HashMap<Integer, String> hMapNumbers = new HashMap<Integer, String>(); /* * This will return true as there are no * mappings stored in the HashMap object */ System.out.println("is empty? " + (hMapNumbers.size() == 0) ); //add key-value pairs hMapNumbers.put(1, "One"); hMapNumbers.put(2, "Two"); hMapNumbers.put(2, "Three"); /* * This will return false as there are 3 * mappings stored in the HashMap object */ System.out.println("is empty? " + (hMapNumbers.size() == 0) ); } } |
Output
1 2 |
is empty? true is empty? false |
What is the best way to check?
Let’s have a look at the source code of both of these methods.
The size method source code:
1 2 3 |
public int size() { return size; } |
The isEmpty method source code:
1 2 3 |
public boolean isEmpty() { return size == 0; } |
In terms of performance, both the approaches should perform the same because both use the internal size member variable. In terms of readability, I would prefer using the isEmpty
method as it clearly states the purpose of the code.
This example is part of the Java HashMap tutorial with examples.
Please let me know your views in the comments section below.