Check If Key Exists in Java Hashtable Example

This example shows how to check if the key exists in the Hashtable in Java. This example also shows how to check if the key exists in Hashtable using the containsKey and get methods.

How to check if the key exists in the Hashtable in Java?

There are a couple of ways to check if the specified key exists in the hashtable object.

1. Using the get method

The Hashtable get method returns the value mapped to the specified key in the hashtable object.

It returns null if the key is not mapped to any value in the hashtable object. We can compare the return value of the get method with null to check if the hashtable contains the key as given below.

Output

2. Using the containsKey method

The Hashtable containsKey method returns true if the specified key exists in the hashtable object.

It returns false if the specified key is not mapped to any value in the hash table object.

Output

How to check if the custom class key exists in the Hashtable in Java?

Let’s see what happens when the hashtable keys are objects of a custom class.

Output

As we can see from the output, even if the key was present in the hashtable, the containsKey method returned false.

The containsKey method relies on the equals method to compare the key objects. If the hashtable contains keys of a custom class, then the custom class must implement the equals and hashCode methods.

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

Output

Which method should I use (get vs containsKey method)?

The containsKey method makes the code more readable and cleaner as compared to comparing the return value of the get method with the null.

However, if you are going to get the value for the key after checking if it exists, using the get method is preferred to save an extra call. In all other scenarios, using the containsKey method is preferred.

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