Check If Value Exists in Java Hashtable Example

This example shows how to check if a value exists in Hashtable in Java. This example also shows how to check if the value exists in the Hashtable using the contains and containsValue methods.

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

There are a couple of ways using which we can check if the hashtable contains the specified value mapped to any key.

1. Using the contains method

The Hashtable contains method returns true if the specified value exists in the hashtable object.

It returns true if the specified value is mapped to one or more keys in the hashtable object. It returns false if the specified value is not mapped to any key in the hash table object.

Output

2. Using the containsValue method

The Hashtable containsValue has the same functionality as the contains method.

it returns true if the specified value is mapped to one or more keys in the hash table, false otherwise.

Output

Which method should I use to check (contains vs containsValue method)?

The contains and containsValue method are similar in functionality. In fact, if you look at the source code of the Hashtable class, the containsValue method simply calls the contains method.

Then why there are two methods? Well, in Java 2 the Hashtable class was rewritten to implement the Map interface. The class implementing an interface must define all the methods declared in the interface so the Hashtable class had to define the containsValue method declared in the Map interface.

How to check if a custom class value exists in Hashtable in Java?

Let’s first see what happens when the hash table values are objects of a custom class.

Output

As we can see from the output, the containsValue method returned false even though the hash table has the specified object. The reason is, the contains and containsValue methods rely on the equals and hashCode methods to compare the objects.

Let’s override these methods in the User class and try again.

Output

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

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

References:
Java 8 Hashtable Documentation

About the author

RahimV

RahimV

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 *

Online Shopping