美文网首页
JDK 8 - computeIfAbsent

JDK 8 - computeIfAbsent

作者: 简了个书1993 | 来源:发表于2018-05-28 18:44 被阅读630次

在使用 Map 时推荐一个不错的函数 computeIfAbsent

/*
 只有在当前 Map 中 key 对应的值不存在或为 null 时
 才调用 mappingFunction
 并在 mappingFunction 执行结果非 null 时
 将结果跟 key 关联.
 mappingFunction 为空时 将抛出空指针异常
*/

// 函数原型 支持在 JDK 8 以上
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

Java

Map<String, List<String>> map = new HashMap<>();
List<String> list;

// 一般这样写
list = map.get("list-1");
if (list == null) {
    list = new LinkedList<>();
    map.put("list-1", list);
}
list.add("one");

// 使用 computeIfAbsent 可以这样写
list = map.computeIfAbsent("list-1", k -> new ArrayList<>());
list.add("one");

Groovy

HashMap<String, List<String>> map = [:]
List<String> list;

// 一般这样写
list = map."list-1"
if (list == null) {
    list = [] as LinkedList
    map."list-1" = list
}
list << "one"

// 使用 computeIfAbsent 可以这样写
list = map.computeIfAbsent("list-1", {[] as LinkedList})
list << "one"

相关文章

网友评论

      本文标题:JDK 8 - computeIfAbsent

      本文链接:https://www.haomeiwen.com/subject/auogjftx.html