Java HashMap computeIfAbsent() Method
The computeIfAbsent() method recalculates the value of the specified key in the HashMap, and adds it to the HashMap if this key does not exist.
The syntax of the computeIfAbsent() method is:
hashmap.computeIfAbsent(K key, Function remappingFunction)
**Note:** hashmap is an object of the HashMap class.
Parameter Description:
- key - the key
- remappingFunction - the remapping function used to recalculate the value
Return Value
If the value corresponding to the key does not exist, it uses the value recalculated by the remappingFunction as the value of this key, otherwise it returns the value.
Example
The following example demonstrates the use of the computeIfAbsent() method:
Example
import
java.util.HashMap
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create a HashMap
HashMap
<
String
, Integer
prices
=
new
HashMap
<>
(
)
;
// Add mappings to the HashMap
prices.
put
(
"Shoes"
,
200
)
;
prices.
put
(
"Bag"
,
300
)
;
prices.
put
(
"Pant"
,
150
)
;
System
.
out
.
println
(
"HashMap: "
prices
)
;
// Calculate the value of Shirt
int
shirtPrice
=
prices.
computeIfAbsent
(
"Shirt"
, key
->
280
)
;
System
.
out
.
println
(
"Price of Shirt: "
shirtPrice
)
;
// Output the updated HashMap
System
.
out
.
println
(
"Updated HashMap: "
prices
)
;
}
}
The output of the above program is:
HashMap: {Pant=150, Bag=300, Shoes=200}
Price of Shirt: 280
Updated HashMap: {Pant=150, Shirt=280, Bag=300, Shoes=200}
In the above example, we created a HashMap named prices.
In the example above, we created a dynamic array named numbers.
prices.computeIfAbsent("Shirt", key -> 280)
In the code, we used the anonymous lambda expression key -> 280 as the remapping function; prices.computeIfAbsent() associates the new value returned by the lambda expression with Shirt.
Because Shirt does not exist in the HashMap, a new key/value pair is added.
To learn more about lambda expressions, please visit To learn more about anonymous functions, please visit.
When the key already exists:
Example
import
java.util.HashMap
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create a HashMap
HashMap
<
String
, Integer
prices
=
new
HashMap
<>
(
)
;
// Add a mapping to the HashMap
prices.
put
(
"Shoes"
,
180
)
;
prices.
put
(
"Bag"
,
300
)
;
prices.
put
(
"Pant"
,
150
)
;
System
.
out
.
println
(
"HashMap: "
prices
)
;
// The mapping for Shoes already exists
// Shoes is not recalculated
int
shoePrice
=
prices.
computeIfAbsent
(
"Shoes"
,
(
key
)
->
280
)
;
System
.
out
.
println
(
"Price of Shoes: "
shoePrice
)
;
// Output the updated HashMap
System
.
out
.
println
(
"Updated HashMap: "
prices
)
;
}
}
The output of the above program is:
HashMap: {Pant=150, Bag=300, Shoes=180}
Price of Shoes: 180
Updated HashMap: {Pant=150, Bag=300, Shoes=180}
In the above example, the mapping for Shoes already exists in the HashMap, so no new value is calculated for Shoes.
Java HashMap