通过merge方法实现HashMap的value自增
解决问题
在水leetcode的时候,想要实现map里指定key对应的value自增的功能。
最开始想到的是之前经常使用的写法:
myMap.put(myKey,myMap.containsKey(myKey)?myMap.get(myKey)+1:1);
忽然想到前几天看到的merge
方法,决得应该会实现得更优雅。搜索发现果然可以:
myMap.merge(myKey, 1, Integer::sum);
Map.merge()
在java.util.Map
可以找到merge方法的源码:
default V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
Objects.requireNonNull(value);
V oldValue = get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if (newValue == null) {
remove(key);
} else {
put(key, newValue);
}
return newValue;
}
可以看到,merge的作用就是:1. 当value参数空时,删除key对应的键值对;2. 判断是否有对应的key,如果没有,插入(key, value);3. 如果原来有对应的key,根据旧值与value计算出新值,插入(key, newValue)。
Integer::sum
public static int sum(int a, int b) { return a + b; }
参考
通过merge方法实现HashMap的value自增
https://blog.loststar.tech/posts/5f2205e5/