JAVA8 Map.computeIfAbsent

JAVA8中Map接口增加computeIfAbsent方法

用于应对key不存在则需要添加的场景

建议的写法

return map.computeIfAbsent(key, k -> V.createFor(k));

不建议的写法

V value = map.get(key);
if (value == null) {
  value = V.createFor(key);
  if (value != null) {
    map.put(key, value);
  }
}
return value;

posted on 2022-04-11 22:39  路过君  阅读(233)  评论(0编辑  收藏  举报

导航