Java HashMap putIfAbsent() Method
The putIfAbsent() method first checks whether the specified key exists. If it does not exist, it inserts the key/value pair into the HashMap.
The syntax of the putIfAbsent() method is:
hashmap.putIfAbsent(K key, V value)
Note:hashmap is an object of the HashMap class.
Parameter Description:
- key - The key
- value - The value
Return Value
If the specified key already exists in the HashMap, the value corresponding to this key is returned. If the specified key does not exist in the HashMap, null is returned.
Note:If the specified key was previously associated with a null value, this method also returns null.
Example
The following example demonstrates the use of the putIfAbsent() method:
Example
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> sites = new HashMap<>();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "Example");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// The key does not exist in the HashMap
sites.putIfAbsent(4, "Weibo");
// The key exists in the HashMap
sites.putIfAbsent(2, "Wiki");
System.out.println("Updated Languages: " + sites);
}
}
Executing the above program produces the following output:
sites HashMap: {1=Google, 2=Example, 3=Taobao}
Updated sites HashMap: {1=Google, 2=Example, 3=Taobao, 4=Weibo}
In the above example, we created a HashMap named sites. Note this line:
sites.putIfAbsent(2, "Wiki");
The key 2 already exists in sites, so the insert operation is not performed.
Other Extensions
Java HashMap