使用 computeifpresent 更新值时,需传入一个接受当前键和值的函数,该函数返回新值。若函数返回非空值,则替换原值;若返回 null,则从 map 中移除该键。此操作是原子性的,适合在多线程环境下安全地基于现有值进行计算。

如何根据旧值计算新值并更新?
通过传入 (k, v) -> newValue 的 Lambda 表达式即可实现。例如将值加 1,只需返回 v + 1。如果希望条件更新,可在 Lambda 中加入判断逻辑,不满足条件时返回原值或 null。

import java.util.HashMap;
import java.util.Map;
public class ComputeExample {
public static void main(String[] args) {
Map<string integer> map = new HashMap();
map.put("count", 10);
// 更新:值加 5
map.computeIfPresent("count", (key, oldValue) -> oldValue + 5);
System.out.println(map.get("count")); // 输出 15
// 条件更新:仅当值为偶数时减 2
map.computeIfPresent("count", (key, oldValue) ->
(oldValue % 2 == 0) ? oldValue - 2 : oldValue
);
System.out.println(map.get("count")); // 输出 13 (15是奇数,不变)
// 移除:返回 null
map.computeIfPresent("count", (key, oldValue) -> null);
System.out.println(map.containsKey("count")); // 输出 false
}
}</string>
与 merge 方法相比有什么优势?
computeIfPresent 仅在键存在时执行,而 merge 在键不存在时会调用 remappingFunction 插入新值。若明确知道键已存在且只想修改,computeIfPresent 更语义化且避免不必要的默认值创建。此外,computeIfPresent 允许直接返回 null 来删除条目,而 merge 需要特殊处理才能删除。

import java.util.HashMap;
import java.util.Map;
public class CompareComputeMerge {
public static void main(String[] args) {
Map<string integer> map = new HashMap();
map.put("a", 10);
// computeIfPresent: 键存在,更新
map.computeIfPresent("a", (k, v) -> v * 2);
System.out.println(map.get("a")); // 20
// computeIfPresent: 键不存在,无操作
map.computeIfPresent("b", (k, v) -> v * 2); // 不会执行
System.out.println(map.containsKey("b")); // false
// merge: 键存在,合并
map.merge("a", 5, (existing, newVal) -> existing + newVal);
System.out.println(map.get("a")); // 25
// merge: 键不存在,插入
map.merge("c", 100, (e, n) -> e + n);
System.out.println(map.get("c")); // 100
}
}</string>
当 computeIfPresent 返回 null 时会发生什么?
当传入的映射函数返回 null 时,computeIfPresent 会从 Map 中移除对应的键值对。这是其设计行为之一,可用于条件删除。注意,只有键存在时才会触发此行为;若键不存在,函数不会被调用,Map 保持不变。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











