YouTip LogoYouTip

Java Hashmap Compute

# Java HashMap compute() Method [![Image 3: Java HashMap](#) Java HashMap](#) The compute() method recalculates the value for a specified key in a HashMap. The syntax for the compute() method is: hashmap.compute(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 compute() method: ## Example import java.util.HashMap; class Main { public static void main(String[] args){ // Create a HashMap HashMap 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); // Print 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: 180Updated HashMap: {Pant=150, Bag=300, Shoes=180 In the example above, we created a HashMap named prices. Note 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/100 as the remapping function. To learn more about lambda expressions, please visit (#). [![Image 4: Java HashMap](#) Java HashMap](#)
← Java Hashmap ComputeifpresentPython3 Os Fdopen β†’