map.computeIfAbsent(x,y)
map中不存在key为x的值时,将y作为value,x作为key放入map中。
代码示例
- 先判断再保存jdk1.8之前
private static void test()
{
Map<String,String> map=new HashMap<>();
map.put("name","张三");
String age=map.get("age");
if(age==null){
map.put("age","15");
}
System.out.println(map.get("age"));
}
- 使用computeIfAbsent
private static void test01()
{
Map<String,String> map1=new HashMap<>();
map1.computeIfAbsent("age",k->"16");
System.out.println(map1.get("age"));
}