9

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?

2 Answers 2

12

The problem is here

(k, v) -> v + 1

You should be doing

(k, v) -> k + v

If you check the implementation of merge it says, remappingFunction.apply(oldValue, value); means the existing value will be the first parameter in which you should add the same number you initialized it with which comes as a second parameter for that function.

Update

6
  • 4
    Note that (k, v) -> k + v can also be expressed as Integer::sum, but that’s a matter of taste…
    – Holger
    Commented Jul 13, 2017 at 9:21
  • Will Integer::sum be performance improvement if used multiple times? I have merge() call 10 times in my code..
    – Nilesh
    Commented Jul 13, 2017 at 9:56
  • @Mritunjay (k+v) will be old value plus new value. But whats new value ?
    – Nilesh
    Commented Jul 13, 2017 at 9:59
  • 3
    @Nilesh new value is always the second parameter of the merge function, in your case 1.
    – Mritunjay
    Commented Jul 13, 2017 at 10:27
  • 2
    (k, v) -> k + v and Integer::sum will have exactly the same performance. The class file might be slightly shorter when you use Integer::sum.
    – Holger
    Commented Jul 14, 2017 at 9:36
6

Completing @Mritunjay answer's, here's an equivalent using compute where you might be able to see the difference:

fruitCounts.compute(fruit, (k,v) -> v == null ? 1 : v + 1) //computing over the value
fruitCounts.merge(fruit, 1, (oldValue, newValue) -> oldValue + 1) //merging over the value
6
  • It's not merging over the key, but over the existent value
    – fps
    Commented Jul 13, 2017 at 15:03
  • It is merging over the value, but the what is very unclear is that instead of doing value+1, it has to be key+1, which I find very counter-intuitive. That's why I'm saying "over the key" instead.
    – Tavo
    Commented Jul 14, 2017 at 0:52
  • 2
    Sure. The thing is that it is not the key, but the value that's already in the map. Using (k, v) -> is what is confusing. If instead you were using (oldValue, newValue) ->, everything would be more clear.
    – fps
    Commented Jul 14, 2017 at 1:05
  • 2
    @Federico Peralta Schaffner: to be fair, the JRE developers made the same mistake when implementing Collectors.toMap(…) (the one without a merge function), reporting the old value as duplicate key.
    – Holger
    Commented Jul 14, 2017 at 9:43
  • 1
    @FedericoPeraltaSchaffner ooohhh, I didn't know that. I'll change it. Thanks for pointing it out!
    – Tavo
    Commented Jul 14, 2017 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.