Java Programming Tutorials

Java programming tutorials with many code examples!

Java Util Map.putIfAbsent(key, value)

java.util.Map.putIfAbsent(key, value)

The method Map.putIfAbsent(key, value) associates the given key with the given value if there is no such association or the current value in map is null. Returns null or the previous value.

Method signature

The signature of the java.util.Map.putIfAbsent(key, value) method is as follows:

default V putIfAbsent(K key, V value)

The method is available since Java 8.


  • K key: key with which associate the value,
  • V value: the value to associate with the key.

Return value

Returns the previous value associated with the key or null when there was no value associated or the value was null (if map implementation allows null values).


  • NullPointerException: when the given key or value is null and the map doesn’t allow null keys or values (optional)
  • UnsupportedOperationException: if the put operation is not supported by this map (optional)
  • ClassCastException: if the class of the specified key or value prevents it from being stored in this map (optional)
  • IllegalArgumentException: if some property of the specified key or value prevents it from being stored in this map (optional)

Example usage

In the following code we use java.util.Map.putIfAbsent(key, value):


import java.util.HashMap;
import java.util.Map;

public class MapExamples {

    public static void main(String[] args) {
        Map<Integer,String> nameForId = new HashMap<>();
        nameForId.put(1, "Kajko");
        nameForId.put(2, null);
        System.out.println("Original map: " + nameForId);

        String previous = nameForId.putIfAbsent(1, "abc");
        System.out.println("Previous value: " + previous);
        System.out.println("No changes: " + nameForId);

        nameForId.putIfAbsent(2, "Kokosz");
        System.out.println("Null updated: " + nameForId);

        nameForId.putIfAbsent(3, "Jagna");
        System.out.println("New key: " + nameForId);

The above code produces the following output:

Original map: {1=Kajko, 2=null}
Previous value: Kajko
No changes: {1=Kajko, 2=null}
Null updated: {1=Kajko, 2=Kokosz}
New key: {1=Kajko, 2=Kokosz, 3=Jagna}


Share with the World!