Java Map.replace
Replace an existing mapping, optionally requiring an expected old value before applying the change.
A simple example
Map.replace
- Start with A = 1
- Do this Replace 1 with 2 if it still matches
- Result A = 2
Syntax
rooms.replace(key, expected, replacement)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaChange a room assignment only if it is still current
A receptionist holds a change slip that moves a class from room A2 to B1. Before updating the board, she checks that the displayed entry still matches the room printed on her slip.
import java.util.HashMap;
import java.util.Map;
class Main {
public static void main(String[] args) throws Exception {
var rooms = new HashMap<>(Map.of("Class", "A2"));
rooms.replace("Class", "A2", "B1");
System.out.println(rooms.get("Class"));
}
}
B1
The expected old room matches, so the replacement succeeds.
Ignore a change slip written before another update
A second receptionist finds an older change slip for the same class. The board already shows a newer assignment, so the outdated slip should leave that room in place.
import java.util.HashMap;
import java.util.Map;
class Main {
public static void main(String[] args) throws Exception {
var rooms = new HashMap<>(Map.of("Class", "B1"));
System.out.println(rooms.replace("Class", "A2", "C3"));
}
}
false
The expected value A2 differs from B1, so the conditional operation returns false.
Change a duty room
The old assignment still matches the room printed on the request. The desk replaces the value only when the recorded value matches the expected one. Which value remains?
What to watch for
The conditional overload compares values for equality. A stale expected value leaves the current mapping intact.