Java Map中compute,computeIfAbsent,computeIfPresent的区别
结论:
compute()
,该方法的作用是向map中添加键值对,无论该键是否存在
。如果存在,则覆盖原来的键值对,如果不存在,则添加新的键值对。computeIfAbsent()
,顾名思义,该方法的作用是向map中添加键值对
,如果不存在
,则添加
;如果存在,则不做任何处理。computeIfPresent()
,同样的顾名思义,该方法的作用是向map中添加键值对
,如果存在
,则添加(即覆盖原来的键值对)
;如果不存在,则不做任何处理。
简单总结:computeIfAbsent()和computeIfPresent()是compute()的加强版,且两者作用刚好相反。
使用示例
public static void main(String[] args) throws InterruptedException {
//01 创建一个map,添加一个元素
Map map = new HashMap<String, String>();
map.put("键", "对应的值");
System.out.println(map); //输出结果 {键=对应的值}
//02 这里的操作等价于 01 的操作 k代表键,v代表值
Map mapCompute = new HashMap<String, String>();
mapCompute.compute("键", (k, v) -> "对应的值");
System.out.println(mapCompute); //输出结果 {键=对应的值}
//03 如果map中不存在等于"键"的k,则添加为"键"的k以及"对应的值"
Map mapComputeIfAbsent = new HashMap<String, String>();
Object o = mapComputeIfAbsent.get("键");
if (o == null) {
mapComputeIfAbsent.put("键", "对应的值");
} else {
System.out.println("什么也不做");
}
System.out.println(mapComputeIfAbsent); //输出结果 {键=对应的值}
//04 这里的操作等价于 03 的操作, v代表值
mapComputeIfAbsent.computeIfAbsent("键", v -> "对应的值");
System.out.println(mapComputeIfAbsent); //输出结果 {键=对应的值}
//map.computeIfPresent()和上面同理,我就不再做演示啦~
}