Collections Intermediate

Atomic map updates with compute and merge

Replace multi-step map lookup and mutation with computeIfAbsent(), compute(), and merge().

✕ Manual lookup and update
List<String> values = groups.get(key);
if (values == null) {
    values = new ArrayList<>();
    groups.put(key, values);
}
values.add(value);
✓ Java 8+
groups.computeIfAbsent(key, ignored -> new ArrayList<>())
        .add(value);
See a problem with this code? Let us know.
⚡

Fewer lookups

Avoids repeated key access.

🧵

Better concurrency semantics

Concurrent maps can perform supported updates atomically.

👁

Clear intent

The initialization rule appears beside the access.

Old Approach
get() + null check + put()
Modern Approach
computeIfAbsent()
Since JDK
8
Difficulty
Intermediate
Atomic map updates with compute and merge
Available

Widely available since JDK 8 (March 2014)

Map computation methods combine lookup and update intent into one operation. Use computeIfAbsent() for lazy initialization, compute() when the new value depends on the existing value, and merge() to combine a supplied value with one already in the map. On concurrent map implementations, supported computations also avoid races caused by separate get() and put() calls.