Java HashMap 怎么通过 replace 替换值
使用 hashmap 的 replace(key, value) 方法可以安全地替换指定键对应的旧值。该方法仅在键已存在且当前值与预期值一致(针对三参数版本)时执行替换,并返回被替换的旧值;若键不存在或条件不满足则返回 null 且不修改映射关系。

单参数 replace 如何工作
调用 map.replace(key, newValue) 会无条件地将 key 对应的值更新为 newValue,前提是 key 必须存在于 Map 中。如果 key 不存在,此操作无效且返回 null。它适用于确定键存在且需要覆盖旧值的场景。

使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
import java.util.HashMap;
import java.util.Map;
public class ReplaceDemo {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
// 替换存在的键 "A"
Integer oldVal = map.replace("A", 10);
System.out.println("Replaced A: " + oldVal); // 输出 1
System.out.println("Map: " + map); // 输出 {A=10, B=2}
// 尝试替换不存在的键 "C"
Integer nullVal = map.replace("C", 30);
System.out.println("Replaced C: " + nullVal); // 输出 null
System.out.println("Map: " + map); // 输出 {A=10, B=2},未改变
}
}三参数 replace 的条件判断机制
当需要确保只有当现有值等于预期值时才进行替换时,应使用 map.replace(key, oldValue, newValue)。该方法会先检查 key 是否存在,再检查其当前值是否通过 equals() 方法与 oldValue 相等。仅当两者都满足时,才将值更新为 newValue 并返回 true;否则返回 false 且保持原状。这常用于并发控制或状态机转换中的原子性检查。
立即学习“Java免费学习笔记(深入)”;
import java.util.HashMap;
import java.util.Map;
public class ConditionalReplaceDemo {
public static void main(String[] args) {
Map<String, String> statusMap = new HashMap<>();
statusMap.put("status", "active");
// 情况1:旧值匹配,成功替换
boolean success1 = statusMap.replace("status", "active", "inactive");
System.out.println("Success: " + success1); // true
System.out.println("New Status: " + statusMap.get("status")); // inactive
// 情况2:旧值不匹配,替换失败
boolean success2 = statusMap.replace("status", "active", "deleted");
System.out.println("Success: " + success2); // false
System.out.println("Status Unchanged: " + statusMap.get("status")); // inactive
}
}

















