Skip to content

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.

Output

How to check if TreeMap contains custom class value?

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

Output

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.

Output

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.

References:
Java 8 TreeMap

About the author

Leave a Reply

Your email address will not be published.