Check If LinkedHashMap Contains Key in Java Example

This example shows how to check if the LinkedHashMap in Java contains a key. The example also shows how to check if the key exists in the LinkedHashMap using the get and containsKey methods.

How to check if the LinkedHashMap contains a key in Java?

1. Using the get method

The get method of the LinkedHashMap class returns the value mapped to the specified key. If the key does not exist in the map, the get method returns null.

You can check the return value of the get method and compare it to a null to see if the key exists or not.


The problem is when your LinkedHashMap contains keys that are mapped to a null value. In that case, getting the value of those keys will return null as well.


Note: This approach is not recommended since it is not reliable if the LinkedHashMap object has null values.

2. Using the containsKey method

The containsKey of the LinkedHashMap class returns true if the map object contains the specified key.

This method returns false if the specified key does not exist in the map object.


As you can see from the output, the containsKey method returns true even if the value mapped to the specified key is null.

If the LinkedHashMap object contains objects of a custom class as the keys, the custom class must implement the equals and hashCode methods as given below.


This example is a part of the LinkedHashMap in Java Tutorial.

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

Java 8 LinkedHashMap

About the author



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 *

Online Shopping