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进行修改
1 2 3 4 5 6 7 8 | 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); } //部分源码的注释 |
下面是部分示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
分类:
Java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!