在使用 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"
网友评论