Library contents

Java Map.replace

Replace an existing mapping, optionally requiring an expected old value before applying the change.

A simple example

Map.replace

  1. Start with A = 1
  2. Do this Replace 1 with 2 if it still matches
  3. Result A = 2
The comparison and the replacement refer to the same key.

Syntax

Java 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.java

Change 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.

ResultB1
Main.java
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"));
    }
}
Output
B1

The expected old room matches, so the replacement succeeds.

Advertisements

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.

Resultfalse
Main.java
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"));
    }
}
Output
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?

GivenRecorded West · replace West with East
Worked resultEast

What to watch for

The conditional overload compares values for equality. A stale expected value leaves the current mapping intact.

Documentation for Map.replace