Java HashMap - putIfAbsent() Method
The java.util.HashMap.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.HashMap.putIfAbsent() method is used to put key-value pairs in the given map.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating hash maps HashMap<Integer, String> MyMap = new HashMap<Integer, String>(); //populating MyMap MyMap.put(101, "John"); MyMap.put(102, "Marry"); MyMap.put(103, "Kim"); //printing MyMap System.out.println("Before putIfAbsent, MyMap contains: " + MyMap); //using putIfAbsent method //key is already associated with some value //will produce no effect MyMap.putIfAbsent(101, "Sam"); //key is not present in the map, hence it //will be included in it with specified value MyMap.putIfAbsent(104, "Jo"); //printing MyMap System.out.println("After putIfAbsent, MyMap contains: " + MyMap); } }
The output of the above code will be:
Before putIfAbsent, MyMap contains: {101=John, 102=Marry, 103=Kim} After putIfAbsent, MyMap contains: {101=John, 102=Marry, 103=Kim, 104=Jo}
❮ Java.util - HashMap