Map merge
将新的值赋值给map(如果不存在)或更新具有给定key的现有值。
Map<Integer, Integer> map = new HashMap<>();
for (Integer n : nums) {
if(map.get(n) != null) {
map.put(n, map.get(n)+1);
} else {
map.put(n, 1);
}
}
Map<Integer, Integer> map = new HashMap<>();
for (Integer n : nums) {
map.merge(n, 1, Integer::sum);
}
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;
}
本文来自博客园,作者:白芷呀,转载请注明原文链接:https://www.cnblogs.com/angelica-duhurica/p/12167149.html