Map PutIfAbsent And ComputeIfPresent

Write conditionally into a Map with putIfAbsent and computeIfPresent, so a first writer wins a slot and later writers adjust existing entries.

JavaData Integrity

Code

snippet
import java.util.HashMap;
import java.util.Map;

public class SlotRegistry {

    public static void main(String[] args) {
        Map<String, String> slots = new HashMap<>();

        // putIfAbsent:键缺席才写入;已有值原样保留,不覆盖
        System.out.println("first in:  " + slots.putIfAbsent("worker-a", "job-1"));
        System.out.println("second in: " + slots.putIfAbsent("worker-a", "job-2"));
        System.out.println("after:     " + slots);

        // computeIfPresent:只在键存在时改写,缺席则返回 null 而不报错
        String bumped = slots.computeIfPresent("worker-a", (k, v) -> v + "-retried");
        System.out.println("bumped:    " + bumped);
        System.out.println("missing:   " + slots.computeIfPresent("worker-x", (k, v) -> "never"));

        // 两者配合:占用用 putIfAbsent,重试用 computeIfPresent,读写路径互不越界
        System.out.println("final:     " + slots);
    }
}

The code piece by piece

Map PutIfAbsent And ComputeIfPresent is built around the class SlotRegistry and the function main.

Points of care

  • A package manager plays no part — each call resolves to a built-in API.

Putting it to use

Signature: public static void main(String[] args)

Output lines are prefixed (first in:, second in:, after:), which lets every printed line be traced back to the step behind it.

Core lines

String bumped = slots.computeIfPresent("worker-a", (k, v) -> v + "-retried");
Map<String, String> slots = new HashMap<>();

Interactive Tools for This Topic

FAQ

What does Map PutIfAbsent And ComputeIfPresent print when run?
Execute the whole file; each printed line is prefixed with a label like `first in:`, `second in:`, `after:`.