The Map.merge () documentation says:
If the specified key is not yet associated with the value or is associated with zero, associates it with the specified non-zero value. Otherwise, replaces the associated value with the results of the given reassignment function or deletes it if the result is zero. This method can be useful when combining multiple matching values for a key. For example, to create or add a string message to a value display.
For example, this code should calculate how many fruits of each type are in the basket:
public static void main(String[] args) {
Map<String, Integer> fruitCounts = new HashMap<>();
List<String> fruitBasket = Arrays.asList(
"Apple", "Banana", "Apple", "Orange", "Mango", "Orange", "Mango", "Mango");
for (String fruit : fruitBasket) {
fruitCounts.merge(fruit, 1, (k, v) -> v + 1);
}
System.out.println(fruitCounts);
}
There are 2 apples, 3 mangoes, 2 oranges and 1 banana, but the actual result:
{Apple=2, Mango=2, Orange=2, Banana=1}
What happened?