1、put
插入或覆盖
map.put(K,V);
2、putIfAbsent
以下情况插入新值
1)key不存在
2)key存在,但value==null
插入新value
map.putIfAbsent(K,V)
//个人理解,相当于
if(!map.containsKey(K)||map.get(K)==null){
map.put(K,V)
}
3、computeIfAbsent
以下情况插入新值
1)key不存在
2)key存在,但value==null
插入新value
与putIfAbsent不同的是,当插入的value==null时,computeIfAbsent是不做插入的,而putIfAbsent做插入。
map.computeIfAbsent(K,v->{return new Object();});
//个人理解,相当于
if(!map.containsKey(K)||map.get(K)==null){
if(V!=null){
map.put(K,V);
}else{
}
}
4、computeIfPresent
只有key存在才做操作
1)新value != null,覆盖原值
2)新value == null,移除对应的key
map.computeIfPresent(K,(k,v)->{return new Object();});
//个人理解,相当于
if(map.containsKey(K)){
if(V!=null){
map.put(K,V);
}else{
map.remove(K);
}
}
5、compute
1)新value != null,有该key的值覆盖,无则插入
2)新value == null,无该key什么都不做,有则移除
map.putIfAbsent(K,V);
//个人理解,相当于
if(V!=null){
map.put(K,V);
}else{
if(map.containsKey(K)){
map.remove(K);
}else{
}
}
测试用例:
@Test
public void test29(){
Map<String,String> mm=new HashMap<>();
mm.putIfAbsent("key1","val1");
mm.putIfAbsent("key11",null);
mm.putIfAbsent("key11","val11");
mm.putIfAbsent("key11","val12");
mm.putIfAbsent("key111",null);
mm.putIfAbsent("key112",null);
mm.computeIfAbsent("key2",v->{return "val2";});
mm.computeIfAbsent("key22",v->{return null;});
mm.computeIfAbsent("key22",v->{return "val22";});
mm.computeIfAbsent("key22",v->{return "val23";});
mm.computeIfAbsent("key222",v->{return null;});
mm.computeIfAbsent("key112",v->{return "val112";});
mm.computeIfAbsent("key3",v->{return "val3";});
mm.computeIfAbsent("key4",v->{return "val4";});
mm.computeIfAbsent("key5",v->{return "val5";});
mm.computeIfAbsent("key5",v->{return "val555";});
mm.computeIfAbsent("key6",v->{return null;});
printMap(mm);
System.out.println();
mm.computeIfPresent("key1",(k,v)->{return "test1";});
// mm.put("key1",null);
mm.computeIfPresent("key100",(k,v)->{return "Test2";});
mm.computeIfPresent("key3",(k,v)->{return null;});
mm.compute("key4",(k,v)->{return "Test3";});
mm.compute("key5",(k,v)->{return null;});
mm.compute("key55",(k,v)->{return null;});
mm.compute("key555",(k,v)->{return "val555";});
printMap(mm);
}
private void printMap(Map<String,String> mm){
Iterator<Map.Entry<String, String>> iterator = mm.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, String> next = iterator.next();
System.out.println("key:"+next.getKey()+" value:"+next.getValue());
}
}
输出:
key:key1 value:val1
key:key2 value:val2
key:key5 value:val5
key:key3 value:val3
key:key4 value:val4
key:key22 value:val22
key:key11 value:val11
key:key112 value:val112
key:key111 value:null
key:key1 value:test1
key:key2 value:val2
key:key4 value:Test3
key:key555 value:val555
key:key22 value:val22
key:key11 value:val11
key:key112 value:val112
key:key111 value:null