📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
HashMap.compute()
method in Java is used to compute a new mapping for the specified key and its current mapped value (or null
if there is no current mapping). This guide will cover the method's usage, explain how it works, and provide examples to demonstrate its functionality.Table of Contents
- Introduction
compute
Method Syntax- Examples
- Updating an Entry in a HashMap
- Real-World Use Case: Updating Product Quantity
- Conclusion
Introduction
The HashMap.compute()
method is a member of the HashMap
class in Java. It allows you to recompute the value associated with a key based on the current mapping (or lack thereof). This can be useful for performing complex updates or conditional modifications to the values in the map.
compute() Method Syntax
The syntax for the compute
method is as follows:
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
- The method takes two parameters:
key
of typeK
, which represents the key whose value is to be computed.remappingFunction
of typeBiFunction<? super K, ? super V, ? extends V>
, which represents the function to compute a new value for the key.
- The method returns the new value associated with the specified key, or
null
if the key is removed from the map.
Examples
Updating an Entry in a HashMap
The compute
method can be used to update the value associated with a key based on its current value.
Example with Lambda Expression
import java.util.HashMap; import java.util.function.BiFunction; public class ComputeExample { public static void main(String[] args) { // Creating a HashMap with String keys and Integer values HashMap<String, Integer> people = new HashMap<>(); // Adding entries to the HashMap people.put("Ravi", 25); people.put("Priya", 30); people.put("Vijay", 35); // Using compute method to update the age of "Ravi" people.compute("Ravi", (key, value) -> (value == null) ? 0 : value + 1); // Using compute method to add a new entry for "Amit" people.compute("Amit", (key, value) -> (value == null) ? 1 : value + 1); // Printing the updated HashMap System.out.println("Updated HashMap: " + people); } }
Output:
Updated HashMap: {Ravi=26, Priya=30, Vijay=35, Amit=1}
Real-World Use Case: Updating Product Quantity
In a real-world scenario, you might use the compute
method to increment the quantity of a product in a product inventory.
Example with Lambda Expression
import java.util.HashMap; public class UpdateProductQuantity { public static void main(String[] args) { // Creating a HashMap with String keys (product IDs) and Integer values (quantities) HashMap<String, Integer> productInventory = new HashMap<>(); // Adding entries to the HashMap productInventory.put("P001", 10); productInventory.put("P002", 15); productInventory.put("P003", 20); // Using compute method to increment the quantity of "P001" productInventory.compute("P001", (key, value) -> (value == null) ? 1 : value + 5); // Using compute method to add a new product "P004" productInventory.compute("P004", (key, value) -> (value == null) ? 1 : value + 5); // Printing the updated product inventory System.out.println("Updated Product Inventory: " + productInventory); } }
Output:
Updated Product Inventory: {P001=15, P002=15, P003=20, P004=1}
Conclusion
The HashMap.compute()
method in Java provides a way to recompute the value associated with a key based on its current value. By understanding how to use this method, you can efficiently perform complex updates and conditional modifications to the values in your map. This method is useful in various scenarios, such as updating records in a database, managing inventory quantities, and handling state transitions in collections.
Comments
Post a Comment
Leave Comment