Java HashMap compute() Method
The compute() method recalculates the value for the specified key in the hashMap.
The syntax of compute() method is:
hashmap.compute(K key, BiFunction remappingFunction)
Note:hashmap is an object of the HashMap class.
Parameter Details:
- 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 using the remappingFunction.
Example
The following example demonstrates the usage 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 mapping entries 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);
}
}
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<String, Integer> prices = new HashMap<>();
// Add mapping entries 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);
}
}
Running the above program produces the output:
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.
Notice the expression:
prices.compute("Shoes", (key, value) -> value - value * 10/100)
In the code, we used an anonymous function - lambda expression(key, value) -> value - value * 10/100as the remapping function.
To learn more about lambda expressions, visitJava Lambda Expressions。
Other Extensions
Java HashMap