What is the Hashtable.putIfAbsent method in Java?

What is a HashTable?

A HashTable is a collection of key-value pairs. The object to be used as a key should implement the hashCode and equals methods, and the key and value should not be null.


You can read about the difference between a HashTable and a HashMap here.

What is the putIfAbsent() method in Hashtable?

The putIfAbsent method adds a key-value pair to the HashTable object if the key is not present in the map.

If the key is already present, then it skips the operation.

Syntax


public V putIfAbsent(K key,V value)

Return value

If the key is already present in the map, then putIfAbsent returns the value associated with the key, and no insertion will be done.

If the key is not present in the map, the key-value pair is inserted and the method returns null.

Code

The code below demonstrates how to use the putIfAbsent method.

import java.util.Hashtable;
class Main {
public static void main( String args[] ) {
// create a Hashtable
Hashtable<Integer, String> numbers = new Hashtable<>();
// add key-value pairs to the Hashtable
numbers.put(1, "one");
numbers.put(2, "Two");
numbers.put(3, "three");
System.out.println("The map is => " + numbers);
System.out.println("\nTrying to add (1, \"ONE\") in the map ");
String value = numbers.putIfAbsent(1, "ONE");
// key - 1 is already present in the map
// so the value associated with the key is returned
System.out.println("The Return value is => " + value);
System.out.println("The map is => " + numbers);
System.out.println("\nTrying to add (4, \"Four\") in the map ");
value = numbers.putIfAbsent(4, "FOUR");
// key - 4 is not already present in the map
// so a new entry with the key as 4 and value as FOUR will be added
// and null is returned
System.out.println("The Return value is => " + value);
System.out.println("The map is => " + numbers);
}
}

Explanation

In the code above:

  • We create a Hashtable with three entries.

  • We attempt to add a new entry to the Hashtable with:

    1. The already existing key 1. In this case, the old value will be returned and the insertion will be skipped.

    2. The new key 4. In this case, the new key-value entry will be inserted and null is returned.

Free Resources