Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java HashMap compute() Method

Java HashMap compute() Method

Java HashMap Java HashMap

The compute() method recalculates the value of the specified key in the HashMap.

The syntax of the compute() method is:


hashmap.compute(K key, BiFunction remappingFunction)

**Note:** hashmap is an object of the HashMap class.

Parameter Description:

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 compute() 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

)

;

       

// Recalculate the value of shoes after a 10% discount

       

int

newPrice

=

prices.

compute

(

"Shoes"

,

(

key, value

)

->

value

value

10

/

100

)

;

       

System

.

out

.

println

(

"Discounted Price of Shoes: "

newPrice

)

;

       

// Output the updated HashMap

       

System

.

out

.

println

(

"Updated HashMap: "

prices

)

;

   

}

}

The output of the above program is:


HashMap: {Pant=150, Bag=300, Shoes=200}
Discounted Price of Shoes: 180
Updated HashMap: {Pant=150, Bag=300, Shoes=180

In the above example, we created a HashMap named prices.

In the example above, we created a dynamic array named numbers.

prices.compute("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 Java HashMap