Learn how to Increment Map Value in Java 8 Using merge() method with examples.
merge() in Java 8 is used to insert a new key-value pair or update an existing value by applying a remapping function such as Integer::sum.
Code Explanation point wise
- Creates an empty HashMap where the key type is String and the value type is Integer.
- The for loop iterates 4 times (i = 0 to i = 3).
- The merge() method uses “total count” as the key and adds 1 to its value on each iteration.
- If the key does not exist, merge() inserts it with the value 1.
- Integer::sum adds the existing value and the new value to update the count.
- Now prints the map output.
import java.util.HashMap;
import java.util.Map;
public class MergeTest {
public static void main(String[] args) {
Map map = new HashMap();
for (int i = 0; i < 4; i++) {
map.merge("total count", 1, Integer::sum);
}
System.out.println(map);
}
}
Output :
{total count=4}
How merge() Method Works in Java 8
The merge() method is used to insert a new value if the key is not present or update the existing value using a remapping function if the key already exists.
Syntax : map.merge(key, value, remappingFunction);
Where:
• key → The key to be inserted or updated.
• value → The value to be used if the key does not exist.
• remappingFunction → A function used to combine the old and new values
FAQ
How do you increment a value in a HashMap?
You can use the merge() method with Integer::sum to increment values efficiently.
Why use merge() instead of get() and put()?
merge() combines retrieval and update logic into a single operation, making the code cleaner and easier to maintain.
Does merge() work if the key does not exist?
Yes. If the key is absent, the provided value is inserted automatically.
Is merge() available before Java 8?
No. The merge() method was introduced in Java 8 as part of the enhanced Map interface.
What is Integer::sum?
Integer::sum is a method reference introduced in Java 8. It refers to the static method:
Integer.sum(int a, int b)