Check If Value Exists in Java TreeMap Example

This example shows how to check if a value exists in the TreeMap object in Java using the containsValue method. The example also shows how to check if TreeMap contains a custom class value.

How to check if the value exists in Java TreeMap using the containsvalue method?

The containsValue method of the TreeMap class returns true if the specified value exists in the map object.

The return type of the containsValue method is a boolean. It returns true if the specified value is mapped to one or more keys in the TreeMap object, false otherwise.


How to check if TreeMap contains custom class value?

Let’s first see an example of TreeMap having custom class value objects.


As you can see from the output, even if the specified Emp value was present in the TreeMap object, the containsValue method returned false. It is because our custom class has not defined the equals method (and preferably the hashCode method as well).

Let’s override these two methods in our Emp class and try again.


As you can see from the output, this time it worked as expected and printed true.

Please also see how to check If a key exists in the TreeMap example.

This example is a part of the Java TreeMap Tutorial with Examples.

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

Java 8 TreeMap

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 *