在使用 Map 時(shí)推薦一個(gè)不錯(cuò)的函數(shù) computeIfAbsent
/*
只有在當(dāng)前 Map 中 key 對(duì)應(yīng)的值不存在或?yàn)?null 時(shí)
才調(diào)用 mappingFunction
并在 mappingFunction 執(zhí)行結(jié)果非 null 時(shí)
將結(jié)果跟 key 關(guān)聯(lián).
mappingFunction 為空時(shí) 將拋出空指針異常
*/
// 函數(shù)原型 支持在 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"