🎓 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 (178K+ 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
computeMethod 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:
keyof typeK, which represents the key whose value is to be computed.remappingFunctionof 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
nullif 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment