🎓 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.merge() method in Java is used to merge a specified value with an existing value associated with a key in the HashMap using a given remapping function. This guide will cover the method's usage, explain how it works, and provide examples to demonstrate its functionality.Table of Contents
- Introduction
mergeMethod Syntax- Examples
- Merging Values in a HashMap
- Real-World Use Case: Updating Product Quantities
- Conclusion
Introduction
The HashMap.merge() method is a member of the HashMap class in Java. It allows you to merge a value associated with a specified key using a given remapping function. If the key is not already present, the method inserts the key-value pair; otherwise, it merges the existing value with the new value using the remapping function.
merge() Method Syntax
The syntax for the merge method is as follows:
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)
- The method takes three parameters:
keyof typeK, which represents the key whose associated value is to be merged.valueof typeV, which represents the value to be merged with the existing value.remappingFunctionof typeBiFunction<? super V, ? super V, ? extends V>, which represents the function to compute the merged value.
- The method returns the new value associated with the specified key, or
nullif the result of the remapping function isnull.
Examples
Merging Values in a HashMap
The merge method can be used to merge values associated with a key in a HashMap.
Example
import java.util.HashMap;
import java.util.function.BiFunction;
public class MergeExample {
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);
// Using merge method to update the age of "Ravi"
people.merge("Ravi", 5, (oldValue, newValue) -> oldValue + newValue);
// Using merge method to add a new entry for "Vijay"
people.merge("Vijay", 35, (oldValue, newValue) -> oldValue + newValue);
// Printing the updated HashMap
System.out.println("Updated HashMap: " + people);
}
}
Output:
Updated HashMap: {Ravi=30, Priya=30, Vijay=35}
Explanation:
- The code creates a
HashMapcalledpeoplewithStringkeys andIntegervalues. - It adds two entries to the map:
Raviwith a value of25andPriyawith a value of30. - The
mergemethod is used to update the value for the keyRavi. The remapping function(oldValue, newValue) -> oldValue + newValueadds5to the existing value25, resulting in30. - The
mergemethod is also used to add a new entry for the keyVijay. SinceVijayis not already present in the map, the value35is directly inserted. - The final
HashMapis printed, showing the updated values.
Real-World Use Case: Updating Product Quantities
In a real-world scenario, you might use the merge method to update the quantities of products in an inventory system.
Example
import java.util.HashMap;
import java.util.function.BiFunction;
public class UpdateProductQuantities {
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);
// Using merge method to add more quantity to "P001"
productInventory.merge("P001", 5, (oldValue, newValue) -> oldValue + newValue);
// Using merge method to add a new product "P003"
productInventory.merge("P003", 20, (oldValue, newValue) -> oldValue + newValue);
// Printing the updated product inventory
System.out.println("Updated Product Inventory: " + productInventory);
}
}
Output:
Updated Product Inventory: {P001=15, P002=15, P003=20}
Explanation:
- The code creates a
HashMapcalledproductInventorywithStringkeys andIntegervalues. - It adds two entries to the map:
P001with a value of10andP002with a value of15. - The
mergemethod is used to update the quantity for the productP001. The remapping function(oldValue, newValue) -> oldValue + newValueadds5to the existing quantity10, resulting in15. - The
mergemethod is also used to add a new productP003with a quantity of20. - The final
HashMapis printed, showing the updated product quantities.
Conclusion
The HashMap.merge() method in Java provides a way to merge a specified value with an existing value associated with a key using a given remapping function. By understanding how to use this method, you can efficiently manage updates and conditional modifications to the values in your map. This method is useful in various scenarios, such as updating inventory quantities, handling state transitions, and managing complex data structures in collections.
Comments
Post a Comment
Leave Comment