Library contents

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

  1. Start with A = 1
  2. Do this Remove A if its value is 1
  3. Result A is absent
The stored value matches the expected value, so the removal proceeds.

Syntax

Java syntax
claims.remove(ticket, expectedOwner)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

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

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

Both the key and expected owner match, so the mapping is removed.

Advertisements

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.

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

GivenHolder Pia · claimant Pia
Worked result0

What to watch for

Removing by key returns the previous value, which can be null even when a null mapping was removed.

Documentation for Map.remove