Java Map.putIfAbsent
Populate a key when it is absent or currently maps to null. An existing non-null value stays in place.
A simple example
Map.putIfAbsent
- Start with A = 1
- Do this Insert A = 2 only if absent
- Result A stays 1
Syntax
bookings.putIfAbsent(seat, customer)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaKeep the first reservation for a seat
Two students ask for the same seat at a school play. The desk enters the requests in order and needs the first confirmed student's name to survive the second request.
import java.util.HashMap;
class Main {
public static void main(String[] args) throws Exception {
var seats = new HashMap<String, String>();
seats.putIfAbsent("A1", "Mira");
seats.putIfAbsent("A1", "Sam");
System.out.println(seats.get("A1"));
}
}
Mira
The second call finds a non-null reservation, so Mira keeps seat A1.
Fill a previously unassigned delivery slot
A delivery planner reserves a row for the morning shift before choosing a driver. Once Lee volunteers, the planner fills the empty assignment with the driver's name.
import java.util.HashMap;
class Main {
public static void main(String[] args) throws Exception {
var shifts = new HashMap<String, String>();
shifts.put("Morning", null);
shifts.putIfAbsent("Morning", "Lee");
System.out.println(shifts.get("Morning"));
}
}
Lee
Java treats the null mapping as available to putIfAbsent.
Reserve the kiln
Two potters ask to use the same afternoon slot. Two people claim the same slot in order. Keep the first recorded name and read it after both requests.
What to watch for
A shared booking system needs a suitable concurrent map or a database constraint for atomic reservations. This example runs in one thread.