put方法
V put(K key, V value);
使用:如果 Map 中 key 对应的 value 不存在,则将键/值对插入到 HashMap 中。否则覆盖原来的键值对,并返回该值
putIfAbsent方法
default V putIfAbsent(K key, V value) {
V v = get(key);
if (v == null) {
v = put(key, value);
}
return v;
}
使用:如果 Map 中 key 对应的 value 不存在,则将键/值对插入到 HashMap 中。否则不覆盖原来的键值对,并返回该值
compute方法
default V compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue = get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (newValue == null) {
// delete mapping
if (oldValue != null || containsKey(key)) {
// something to remove
remove(key);
return null;
} else {
// nothing to do. Leave things as they were.
return null;
}
} else {
// add or replace old mapping
put(key, newValue);
return newValue;
}
}
使用:不管 Map 中 key 对应的 value 存不存在,都会将 mappingFunction 计算产生的值作为该 key 的 value 进行保存,并返回该值 注意:mappingFunction 中的用到value作为映射计算时需要判空处理,否则会报空指针
HashMap<String,Integer> map = new HashMap<>();
map.put("1",1);
map.put("2",2);
map.put("3",3);
Integer value1 = map.compute("3", (k,v) -> v+1 );
Integer value2 = map.compute("4", (k,v) -> 4*5 );
//key不管存在不在都会执行后面的函数,并保存到map中
Integer value3 = map.compute("5", (k,v) -> {
if (v==null)return 0;
return v+1;
} );
System.out.println(value1);
System.out.println(value2);
System.out.println(value3);
System.out.println(map.toString());
打印结果
4
20
0
{1=1, 2=2, 3=4, 4=20, 5=0}
computeIfAbsent(K key, V value)方法
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
if ((v = get(key)) == null) {
V newValue;
if ((newValue = mappingFunction.apply(key)) != null) {
put(key, newValue);
return newValue;
}
}
return v;
}
使用:如果 Map 中 key 对应的 value 不存在,则会将 mappingFunction 计算产生的值作为该 key 的 value 进行保存,并返回该值。否则不作任何计算,将会直接返回 key 对应的 value
# computeIfPresent方法
default V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue;
if ((oldValue = get(key)) != null) {
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null) {
put(key, newValue);
return newValue;
} else {
remove(key);
return null;
}
} else {
return null;
}
}
使用:如果 Map 中 key 对应的 value 不存在,则返回该 null。否则会将 mappingFunction 计算产生的值作为该 key 的 value 进行保存,并返回该值