Map computeIfAbsent与computeIfPresent区别

Map接口

  default V computeIfAbsent(K key,Function<? super K, ? extends V> mappingFunction)

  上述方法:如果get的value==null,把 computeIfAbsent 方法第二个参数计算value 进行put操作

          如果有值,不做任何操作

1 if (map.get(key) == null){ 
2       V newValue = mappingFunction.apply(key);
3       if (newValue != null)
4          map.put(key, newValue);   
5 } //部分源码的注释

  default V computeIfPresent(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)

  上述方法:如果get的value==null不作任何操作

       如果有值,把 computeIfPresent方法第二个方法可以对value进行修改

if (map.get(key) != null) {
       V oldValue = map.get(key);
       V newValue = remappingFunction.apply(key, oldValue);
       if (newValue != null)
           map.put(key, newValue);
       else
           map.remove(key);   
} //部分源码的注释

 

下面是部分示例

HashMap<Object, Object> map = new HashMap<>();
map.put("AAA","111");  map.put("AAA1","111");
Object aaa = map.computeIfAbsent("AAA", o -> "wqdqwdwq");
Object ccc = map.computeIfAbsent("CCC", o -> "333");
Object a1 = map.computeIfPresent("AAA1", (o, o2) -> o2 + "ASDASDASDSA");
Object a2 = map.computeIfPresent("CCC1", (o, o2) -> o2 + "ASDASDASDSA");
System.err.println(aaa);
System.err.println(ccc);
System.err.println("------");
System.err.println(a1);
System.err.println(a2);

111
333
------
111ASDASDASDSA
null 
posted @ 2022-02-15 17:45  铁柱97  阅读(384)  评论(0)    收藏  举报