Java Utility Library

Java Hashtable - putIfAbsent() Method



The java.util.Hashtable.putIfAbsent() method returns null and associate the specified key with the given value if the specified key is not already associated with a value (or is mapped to null), else returns the current value.

Syntax

public V putIfAbsent(K key, V value)

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

key Specify the key with which the specified value is to be associated.
value Specify the value to be associated with the specified key.

Return Value

Returns the previous value associated with the specified key, or null if there was no mapping for the key. (A null return can also indicate that the map previously associated null with the key, if the implementation supports null values.)

Exception

NA.

Example:

In the example below, the java.util.Hashtable.putIfAbsent() method is used to put key-value pairs in the given hashtable.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating hashtable
    Hashtable<Integer, String> Htable = new Hashtable<Integer, String>();

    //populating hashtable
    Htable.put(101, "John");
    Htable.put(102, "Marry");
    Htable.put(103, "Kim");

    //printing hashtable
    System.out.println("Before putIfAbsent, Htable contains: " + Htable);    

    //using putIfAbsent method
    //key is already associated with some value
    //will produce no effect
    Htable.putIfAbsent(101, "Sam"); 
    //key is not present in the map, hence it 
    //will be included in it with specified value
    Htable.putIfAbsent(104, "Jo"); 

    //printing hashtable
    System.out.println("After putIfAbsent, Htable contains: " + Htable);  
  }
}

The output of the above code will be:

Before putIfAbsent, Htable contains: {103=Kim, 102=Marry, 101=John}
After putIfAbsent, Htable contains: {104=Jo, 103=Kim, 102=Marry, 101=John}

❮ Java.util - Hashtable