Library contents

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

  1. Start with A = 1
  2. Do this Insert A = 2 only if absent
  3. Result A stays 1
The key already exists, so the original value is kept.

Syntax

Java syntax
bookings.putIfAbsent(seat, customer)
Run these examples in Java

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

java Main.java

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

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

The second call finds a non-null reservation, so Mira keeps seat A1.

Advertisements

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.

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

GivenFirst Lin · next Bo
Worked resultLin

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.

Documentation for Map.putIfAbsent