前言:
- 简化基于map中key是否存在,然后采取不同处理策略的场景
Map.computeIfAbsent
// computeIfAbsent:
// key不存在时,创建sets添加‘456’。
String key = "imgs_nos";
Map> map = new HashMap<>();
map.computeIfAbsent(key, (k) -> Sets.newHashSet()).add("456");
// {"imgs_nos":["456"]}
System.out.println(JSONObject.toJSONString(map));
// key存在时,追加‘456’。
map = new HashMap<>();
map.put(key, Sets.newHashSet("123"));
map.computeIfAbsent(key, (k) -> Sets.newHashSet()).add("456");
// {"imgs_nos":["456","123"]}
System.out.println(JSONObject.toJSONString(map));
Map.computeIfPresent
//computeIfPresent:
//key不存在时,NullPointerException
try{
map = new HashMap<>();
map.computeIfPresent(key, (k, v) -> Sets.newHashSet()).add("456");
System.out.println(JSONObject.toJSONString(map));
}catch (NullPointerException ex){
//null
System.out.println(ex.getMessage());
}
//key存在时,新创建sets添加‘456’。
map = new HashMap<>();
map.put(key, Sets.newHashSet("123"));
map.computeIfPresent(key, (k, v) -> Sets.newHashSet()).add("456");
// {"imgs_nos":["456"]}
System.out.println(JSONObject.toJSONString(map));
加时:compute
// compute:
String key = "imgs_nos";
Map> map = new HashMap<>();
map.compute(key, (k, v) -> {
if (v != null) {
v.add("456");
}
return v;
});