Check If LinkedHashMap is Empty in Java Example

This example shows how to check if the LinkedHashMap is empty in Java. This example also shows how to use the isEmpty method and size method to check if the LinkedHashMap is empty or not.

How to check if LinkedHashMap is empty in Java?

There are a couple of ways we can check if the LinkedHashMap is empty or not.

1. Using the isEmpty method

The isEmpty method of the LinkedHashMap class returns true if the map object is empty.

The isEmpty method returns false if is at least one key-value mapping in the LinkedHashMap object.

Output

2. Using the size method

You can also use the size method of the LinkedHashMap class to check if the map is empty or not.

If the LinkedHashMap size is zero then the map is empty, otherwise not.

Output

What is the preferred way to check?

There is no significant difference between these two methods as far as performance is concerned. The isEmpty method internally uses the size to determine if the map is empty.

Using the isEmpty method is the preferred way to check as it makes code look cleaner and makes the purpose of the code clear as compared to the size method approach.

This example is a part of the Java LinkedHashMap tutorial with examples.

Please let me know your views in the comments section below.

References:
Java 8 LinkedHashMap

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 *