Skip to content

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.

Output

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.

Output

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.

Output

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.

Output

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

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

References:
Java 8 LinkedHashMap

About the author

Leave a Reply

Your email address will not be published.