[Java] How to increment Map value with 1 line in Java

1 minute read

How to write (Java8 or later)

How to write


map.merge(key, 1, Integer::sum);

Try to move

example


jshell> Map<String, Integer> map = new HashMap<>();
map ==> {}

jshell> map.put("apple", 0);
$2 ==> null

jshell> map.get("apple");
$3 ==> 0

jshell> map.merge("apple", 1, Integer::sum);
$4 ==> 1

jshell> map.get("apple");
$5 ==> 1

jshell> map.merge("apple", 1, Integer::sum);
$6 ==> 2

jshell> map.get("apple");
$7 ==> 2

why?

Let’s check sum method of Integer and merge method of Map

Integer.sum

It just adds the two arguments.

sum public static int sum(int a, int b) Adds two integers, like the + operator. Parameters: a-First operand b-Second operand Return value: sum of a and b Introduced version: 1.8

Oracle documentation

Map.merge

default V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) Associates the specified key with the specified non-null value if it is not already associated with a value or is associated with null. Otherwise, it replaces the associated value with the result of the specified remapping function and removes it if the result is null.

Oracle documentation

In other words, the value of the second argument, value, is the default value if it is null, and if it is not null, the result of the function of the third argument is set.

The third argument function also takes two arguments. The first argument of the third argument function is the value for key. The second argument of the function of the third argument is the value when the same value as the second argument is null.

[Java] Map#merge is hard to understand.

Is it like this if you name the variable?

map.merge(key, defaultValue, (value, defaultValue) -> function());

That is?

map.merge(key, 1, Integer::sum) treats the default value like step (the number that is added in one process), and sums the value and the default value with the sum of Integer by the method reference. I am.

Reference

https://stackoverflow.com/questions/81346/most-efficient-way-to-increment-a-map-value-in-java

Also, when I read “Effective Java 3rd Edition”, this method was also mentioned in Item 43: Select method reference over lambda (P199).

Tags:

Updated: