Skip to content

Java Hashtable Get Value for a Key using get and getOrDefault methods

This example shows how to get the value for a key from Java Hashtable using the get method and getOrDefault method.

How to get the value for a key from Hashtable 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 specified key does not exist in the hashtable object.

Output

How to get the value for a key from Hashtable using the getorDefault method?

As we can see from the previous output, the Hashtable get method returns null if the specified key is not mapped to any value in the hash table object.

If you want to get a default value instead of a null if the key does not exist in the hash table object, then you can use the Hashtable getOrDefault method.

The getOrDefault method returns the value mapped to the given key if the key exists in the hashtable object. If the key does not exist, it returns the specified default value instead of a null.

Output

Important Note:

The Hashtable get and getOrDefault methods throw NullPointerException exception if the specified key is null. Unlike the HashMap class in Java, the Hashtable class does not allow null keys or values.

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

Leave a Reply

Your email address will not be published.