- computeIfAbsent的方法有两个参数 第一个是所选map的key,第二个是需要做的操作。这个方法当key值不存在时才起作用。
- 当key存在返回当前value值,不存在执行函数并保存到map中
public class MapComputeIfAbsent {
public static void main(String[] args) {
HashMap<String,Integer> map = new HashMap<>();
map.put("1",1);
map.put("2",2);
map.put("3",3);
Integer integer = map.computeIfAbsent("3", key -> new Integer(4));
Integer integer1 = map.computeIfAbsent("4", key -> new Integer(4));
System.out.println(integer);
System.out.println(integer1);
System.out.println(map.toString());
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191015203204882.png)