Java Hashmap Putifabsent
# Java HashMap putIfAbsent() Method
[ Java HashMap](#)
The putIfAbsent() method first checks if the specified key exists. If it does not exist, it inserts the key/value pair into the HashMap.
The syntax for 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, it returns the value associated with that key. If the specified key does not exist in the HashMap, it returns null.
**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
import java.util.HashMap;
class Main {
public static void main(String[] args){
// Create a HashMap
HashMap sites =new HashMap();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "");
sites.put(3, "Taobao");
System.out.println("sites HashMap: "+ sites);
// Key does not exist in HashMap
sites.putIfAbsent(4, "Weibo");
// Key exists in HashMap
sites.putIfAbsent(2, "Wiki");
System.out.println("Updated Languages: "+ sites);
}
}
The output of the above program is:
sites HashMap: {1=Google, 2=, 3=Taobao}Updated sites HashMap: {1=Google, 2=, 3=Taobao, 4=Weibo}
In the example above, we created a HashMap named `sites`. Note this line:
sites.putIfAbsent(2, "Wiki");
The key `2` already exists in `sites`, so the insertion operation is not performed.
[ Java HashMap](#)
YouTip