How to write
map.merge(key, 1, Integer::sum);
Illustrative
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
Let's examine the sum method of Integer and the merge method of Map
Integer.sum
It's just adding 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
Map.merge
default V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) If the specified key is not yet associated with a value or is associated with null, it will be associated with the specified non-null value. Otherwise, it replaces the relevant value with the result of the specified remapping function and removes it if the result is null.
In other words, the second argument value
is the default value if it is null, otherwise the result of the function of the third argument is set.
The function with the third argument also takes two arguments. The first argument of the function of the third argument is the value for the 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 when you give a name to a variable?
map.merge(key, defaultValue, (value, defaultValue) -> function());
map.merge (key, 1, Integer :: sum)
treats the default value like a step (the number added in one process), and sums the value and the default value with the sum of Integer by the method reference. I am.
https://stackoverflow.com/questions/81346/most-efficient-way-to-increment-a-map-value-in-java
Also, when I read "Effective Java 3rd Edition", this writing method was also mentioned in Item 43 Choosing a method reference over Lambda (P199).
Recommended Posts