JDK 8 - computeIfAbsent

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

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

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


Java

Map> map = new HashMap<>();
List 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> map = [:]
List 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)