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 HashMapHashMap<Integer, String> numbers = new HashMap<>();// add key-value pairs to the HashMapnumbers.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 returnedSystem.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 returnedSystem.out.println("The value is => " + value);System.out.println("The map is => " + numbers);}}
Explanation
In the code above:
-
We created a
HashMapwith three entries. -
We attempted to add a new entry to the
HashMapwith:-
The already existing
key1.In this case, the old value will be returned and the insertion will be skipped.
-
The new
key4.In this case, the new key-value entry will be inserted and the
nullis returned.
-