JDK8新增的Map的computeIfAbsent介绍
前言
今天在sonar扫描代码的时候,报了一个问题“Replace this Map.containsKey()” with a call to “Map.computeIfAbsent()”,了解发现是JDK8新增的Map的computeIfAbsent方法,这里做一个简单的记录。
一、sonar扫描有问题的代码
String key = "test";
Map<String, List<String>> map = new HashMap<>();
List<String> list = new ArrayList<>();
if (map.containsKey(key)) {
list = map.get(key);
}
list .add("测试");
map.put(key, list);
二、使用computeIfAbsent方法
String key = "test";
Map<String, List<String>> map = new HashMap<>();
List<String> list = map.computeIfAbsent(key, e -> new ArrayList<>());
list.add("特殊");
三、源码
// 从map中获取对应键值,获取不到则执行Function, Function的结果放入map中,并将该结果返回。
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
// 获取的value不存在
if ((v = get(key)) == null) {
V newValue;
// 执行Function获取新值,放入Map中并返回
if ((newValue = mappingFunction.apply(key)) != null) {
put(key, newValue);
return newValue;
}
}
// 存在则直接返回
return v;
}