Skip to content

Java Hashtable put, putIfAbsent, putAll Methods Example

This example shows how to use Java Hashtable put, putIfAbsent, and putAll method to add key-value mappings or entries in the hashtable object.

How to add new key-value mappings to Hashtable using the put method?

The Hashtable put method maps the specified key to the specified value in the hashtable object.

If the specified key already exists in the hash table, the put method replaces the old value with the specified new value and returns the old value. if the key does not exist, it creates a new mapping and returns null.

Output

How to add new key-value mappings to Hashtable using the putIfAbsent method?

As we can see from the previous output, the put method replaces an old value with the specified new value if the key already exists in the hashtable object.

If you want to add a new mapping if the key does not exist but do not want to replace the value if the key already exists, then you can use the Hashtable putIfAbsent method.

The putIfAbsent method maps the specified key to the specified value if the key does not already exist in the hashtable and returns null. if the key already exists, it simply returns the existing value associated with the given key and does not do any replacement.

Output

As we can see from the output, the putIfAbsent method does not replace the value if the key is already present in the hashtable.

How to copy mappings from any map object to Hashtable using the putAll method?

The Hashtable putAll method copies all the mappings of the specified map object to this hashtable object.

The mappings contained in the specified map will replace the mappings in the hashtable for the matching keys.

The below given example shows how to copy all mappings from the HashMap class object to the hashtable object using the putAll method.

Output

As we can see from the output, the value “Ten” for key 1 in the hashtable was replaced by the value “One” in the hashmap object.

Important Note:

The Hashtable class does not allow null keys or values. The put, putIfAbsent, and putAll methods throw NullPointerException if any key or value is specified as null.

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.