English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java HashMap compute() method calculates a new value and associates it with the specified key in the hash map.
The syntax of the compute() method is:
hashmap.compute(K key, BiFunction remappingFunction)
The compute() method has two parameters:
key - Key associated with the calculated value
remappingFunction - For the specifiedKeyFunction to calculate the new value
NoteThe remappingFunction can accept two parameters.
Return the new value associated with the key
If there is no associated value for the key, return null
NoteIf the remappingFunction result is null, the specifiedKeymapping.
import java.util.HashMap; class Main { public static void main(String[] args) { //Creating HashMap HashMap<String, Integer> prices = new HashMap<>(); //Inserting entries into the HashMap prices.put("Shoes", 200); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("HashMap: ") + prices); //With10Percentage discount to recalculate the price of the shoes int newPrice = prices.compute("Shoes", (key, value) -> value - value * 10/100); System.out.println("Discounted shoe price: ") + newPrice); //Print the updated HashMap System.out.println("Updated HashMap: ") + prices); } }
Output result
HashMap: {Pant=150, Bag=300, Shoes=200} Discounted shoe price: 180 Updated HashMap: {Pant=150, Bag=300, Shoes=180
In the above example, we created a hash map named prices. Note the expression
prices.compute("Shoes", (key, value) -> value - value * 10/100)
Here,
(key, value) -> value - value * 10/100 - This is a lambda expression. It will reduce the original price of the shoes10% and return. For more information on lambda expressions, please visitJava Lambda Expressions.
prices.compute() - Associate the new value returned by the lambda expression with the Shoes mapping.
NoteAccording to the official Java documentation,HashMap merge()The method is simpler than the compute() method.
Recommended Reading
HashMap computeIfAbsent() - Compute the value if the specified key is not mapped to any value
HashMap computeIfPresent() - Compute the value if the specified key is already mapped to a value