Check if HashMap is Empty Example

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.

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.

Output

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.

Output

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:

The isEmpty method source code:

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.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *