Java HashMap computeIfPresent() Method
The computeIfPresent() method recalculates the value of the specified key in the HashMap, provided that the key exists in the HashMap.
The syntax of the computeIfPresent() method is:
hashmap.computeIfPresent(K key, BiFunction 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 returns null; if it exists, it returns the value recalculated by the remappingFunction.
Example
The following example demonstrates the use of the computeIfPresent() method:
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"
,
200
)
;
prices.
put
(
"Bag"
,
300
)
;
prices.
put
(
"Pant"
,
150
)
;
System
.
out
.
println
(
"HashMap: "
prices
)
;
// Recalculate the value of shoes plus 10% VAT
int
shoesPrice
=
prices.
computeIfPresent
(
"Shoes"
,
(
key, value
)
->
value
value
10
/
100
)
;
System
.
out
.
println
(
"Price of Shoes after VAT: "
shoesPrice
)
;
// 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 Shoes after VAT: 220
Updated HashMap: {Pant=150, Bag=300, Shoes=220}}
In the above example, we created a HashMap named prices.
In the example above, we created a dynamic array named numbers.
prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100)
In the code, we used the anonymous lambda expression (key, value) -> value + value * 10/100 as the remapping function.
To learn more about lambda expressions, please visit To learn more about anonymous functions, please visit.
Java HashMap