computeifabsent 可避免手动判空+put,适用于“获取值、不存在则创建并缓存”场景;它只在 key 不存在时执行 function 计算并存入,参数为 key 和 function。

直接用 computeIfAbsent 可以避免手动判空 + put 的冗余代码,尤其适合“获取值,不存在则创建并缓存”的场景。
核心用法:只在 key 不存在时计算并放入
computeIfAbsent 接收两个参数:key 和一个 Function super K, ? extends V>。它会先检查 key 是否存在:
- 存在 → 直接返回已有 value,不执行函数
- 不存在 → 执行函数生成新 value,put 进 map 并返回该值
注意:函数只在真正需要时才调用,线程安全(HashMap 本身不保证线程安全,但该方法内部对单次操作是原子的)。
替代 if-else 判空的经典写法
比如缓存用户订单列表:
if (!map.containsKey(userId)) {
map.put(userId, new ArrayList());
}
List<order> orders = map.get(userId);</order>
// ✅ computeIfAbsent 一行搞定List<order> orders = map.computeIfAbsent(userId, k -> new ArrayList());</order>
更进一步,如果初始化逻辑稍复杂(如查库、构造对象),也能自然嵌入:
UserProfile profile = cache.computeIfAbsent(userId,
id -> loadUserProfileFromDB(id)); // 只在首次访问时调用
注意事项和常见坑
-
函数不能返回 null:否则抛
NullPointerException(JDK 8+ 行为) -
不要在 lambda 中修改 map 自身:可能引发
ConcurrentModificationException或死循环 -
HashMap 非线程安全:高并发下建议用
ConcurrentHashMap,它的computeIfAbsent是线程安全的 -
key 为 null 时行为取决于实现:HashMap 允许 null key,但
computeIfAbsent(null, ...)会正常工作;ConcurrentHashMap 不允许 null key,会直接抛 NPE
实用技巧:配合 Supplier 或方法引用简化
如果构造逻辑已封装好,可用方法引用提升可读性:
// 假设有静态工厂方法
map.computeIfAbsent(userId, UserOrderList::new);
// 或使用 Supplier 匿名类(Java 7 风格,少用)
map.computeIfAbsent(userId, new Function() {
public List<order> apply(Integer k) { return new ArrayList(); }
});</order>
对于简单对象,甚至可以链式调用(如构建 builder):
Config cfg = configs.computeIfAbsent("dev",
k -> Config.builder().env(k).timeout(5000).build());Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











