Skip to content

Java Check if value exists in HashMap Example

This example shows how to check if a value exists in the HashMap in Java using the containsValue method. The example also shows how to check if HashMap has value if the value is an object of a custom class.

How to check if a value exists in HashMap in Java?

The containsValue method of the Java HashMap class returns true if the map contains the specified value mapped to any key.

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

Output

How to check if HashMap has the value of a custom class?

Let’s see what happens when we use an object of a custom class as the value of the HashMap.

Output

As you can see from the output, even though the map has the specified value object, the containsvalue method returns false. It is because of the containsValue method which relies on the equals method.

The Rectangle class I used in the example has not implemented the equals and hashCode methods so it inherits these methods from the superclass Object. The Object class version of the equals method compares the references so it returns false as the references are different.

In order for the containsValue method to work correctly, we need to implement the equals and hashCode methods in our custom class as given below.

Output

As you can see from the output above, the containsValue worked as expected after implementing the equals and hashCode methods in the custom Rectangle class. Please also see how to check if key exists in HashMap example.

This example is part of the HashMap in Java tutorial.

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

About the author

Leave a Reply

Your email address will not be published.