To Increment a Map Value in Java 8, we are using HashMap merge() Method.
- The HashMap merge() method used to compute the new updated value that will replace the existing value in the Map.
- Here we iterate a for loop from 0 to 4.
- Inside Merge method, we mention “total count” as a key and value will be increment each time during iteration using Integer::sum method.
- Integer::sum method handles update or add values associated with keys.
- Now print the output.
import java.util.HashMap;
import java.util.Map;
public class MergeTest {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < 4; i++) {
map.merge("total count", 1, Integer::sum);
}
System.out.println(map);
}
}
Output :-
{total count=4}