What is HashMap.putIfAbsent in Java?

Overview

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

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

Syntax


Hashmap.putIfAbsent(key, value);

Return value

If the key is already present in the map, then the value associated with the key is returned and insertion will be skipped.

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

Code

import java.util.HashMap;
class Main {
public static void main( String args[] ) {
// create a HashMap
HashMap<Integer, String> numbers = new HashMap<>();
// add key-value pairs to the HashMap
numbers.put(1, "one");
numbers.put(2, "two");
numbers.put(3, "three");
System.out.println("The map is => " + numbers);
System.out.println("Trying 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 value is => " + value);
System.out.println("Trying to add (4, \"Four\") in the map ");
value = numbers.putIfAbsent(4, "FOUR");
// key - 4 is nootalready 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 value is => " + value);
System.out.println("The map is => " + numbers);
}
}

Explanation

In the code above:

  • We created a HashMap with three entries.

  • We attempted to add a new entry to the HashMap with:

    • The already existing key 1.

      In this case, the old value will be returned and the insertion will be skipped.

    • The new key 4.

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

Free Resources