The Map.merge() documenation says:
If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. This method may be of use when combining multiple mapped values for a key. For example, to either create or append a String msg to a value mapping.
For example, this code should calculate how many fruits of each type there are in a 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/*First fruit of this type*/, (k, v) -> v + 1);
}
System.out.println(fruitCounts);
}
There are 2 Apples, 3 Mangos, 2 Oranges and 1 Banana but the actual output is:
{Apple=2, Mango=2, Orange=2, Banana=1}
What is wrong?