Java HashMap putIfAbsent() Method
The putIfAbsent() method first checks whether the specified key exists; if not, 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, it returns the value corresponding to this 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
<
Integer
, String
sites
=
new
HashMap
<>
(
)
;
// Add some elements to the HashMap
sites.
put
(
1
,
"Google"
)
;
sites.
put
(
2
,
"Runoob"
)
;
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
)
;
}
}
The output of the above program is:
sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
Updated sites HashMap: {1=Google, 2=Runoob, 3=Taobao, 4=Weibo}
In the above example, we created a HashMap named sites. Note this line:
sites.putIfAbsent(2, "Wiki");
Key 2 already exists in sites, so the insertion is not performed.
Java HashMap