Skip to content

Check If LinkedHashMap Contains Value in Java Example

This example shows how to check if the LinkedHashMap contains the specified value in Java. The example also shows how to check if the value exists in the LinkedHashMap using the containsValue method.

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

The containsValue method of the LinkedHashMap class returns true if the specified value is mapped to any of the keys in the LinkedHashMap object.

The containsValue method returns false if the specified value is not mapped to any key in the map.

Output

How to check if the LinkedHashMap values are objects of a custom class?

If the LinkedHashMap values are objects of a custom class, then the custom class must implement the equals method (and preferably the hashCode method too).

Output

As you can see from the output, the containsValue method returns false even though the value was present in the LinkedHashMap object. It is because our Emp class has not implemented the equals method. Let’s implement it and try again.

Output

Now the containsValue method worked as expected and returned true.

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.