Remove Key Value Mapping from Hashtable in Java Example

This example shows how to remove key-value mapping or entry from the Hashtable in Java. This example also shows how to remove hashtable entry using the remove method.

How to remove a key-value mapping or entry from the Hashtable in Java?

The Hashtable remove method removes the specified key and the value associated with it from the hashtable object.

It returns the value mapped to the given key if the specified key is found and removed from the hashtable, null otherwise.

Output

The above given remove method removes the key-value from the hashtable if the key is mapped to any value in the hashtable. If you want to remove the entry only if the key is mapped to a specific value, you can use the below given overloaded remove method.

It removes the entry if and only if the given key is mapped to the given value in the hashtable and returns true. If the given key does not exist or the key is not mapped to the given value, it returns false.

Output

How to remove key-value mappings from the Hashtable of custom class objects?

Let’s try to remove an entry from the hashtable having keys of a custom class.

Output

As we can see from the output, even if the hashtable contains the key, the remove method returns null and does not remove the entry from the hashtable.

The remove method relies on the equals and hashCode methods to compare and find the object to be removed. Since the User class has not overridden these methods, methods inherited from the Object class were called which compare the object references, not the actual content. That was the reason the remove method could not find the key in the hashtable object.

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

Output

Tip: Always override the equals and hashCode methods in the custom classes while working with any Java Collection classes.

This example is a part of the Java Hashtable 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