Java Map.remove
Remove an entry by key or require that its current value also match. Conditional removal returns a boolean.
A simple example
Map.remove
- Start with A = 1
- Do this Remove A if its value is 1
- Result A is absent
Syntax
claims.remove(ticket, expectedOwner)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRelease a locker only for its recorded owner
A school uses locker numbers as keys and student names as values. When Mira returns her locker, the desk clears the assignment only if the current register still names Mira.
import java.util.HashMap;
import java.util.Map;
class Main {
public static void main(String[] args) throws Exception {
var claims = new HashMap<>(Map.of("L2", "Mira"));
System.out.println(claims.remove("L2", "Mira") ? "Released" : "Check owner");
}
}
Released
Both the key and expected owner match, so the mapping is removed.
Read the name on a collected parcel
A customer collects a parcel from the service counter. The clerk removes its ticket from the waiting register and prints the name previously attached to that ticket.
import java.util.HashMap;
import java.util.Map;
class Main {
public static void main(String[] args) throws Exception {
var parcels = new HashMap<>(Map.of("P8", "Sam"));
System.out.println(parcels.remove("P8"));
}
}
Sam
Removing by key returns the previous recipient so it can be printed on the collection slip.
Return a locker key
A locker has a single claim and its registered holder returns the key. The clerk removes the claim only when the recorded owner matches the claimant. How many claims remain?
What to watch for
Removing by key returns the previous value, which can be null even when a null mapping was removed.