compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) is another alternative available since Java 1.8. It accepts the following arguments:

A key A remapping BiFunction : The first argument is the key The second argument is the current value The return value is the new computed value

Like merge() , if the value returned by the BiFunction is null , the mapping will be removed.

The above code can be rewritten with compute() like the following:

map . compute ( key , ( aKey , value ) -> { if ( value == null ) { return 1 ; } else { return ++ value ; } });

Differences between compute() and merge() are subtle but important. With the former, the BiFunction will be called in any case, while with the latter, it will only if the value is not null . Also, note that the BiFunction arguments refers to different arguments depending on the method.

If and only if the value is guaranteed to not be null , the above code can be rewritten as:

map . compute ( key , ( aKey , value ) -> ++ value );

To make sure this assumption holds true, a dedicated method is also available, computeIfPresent() wit the same arguments:

map . computeIfPresent ( key , ( aKey , value ) -> ++ value );