CollectionsMaps
Java 8+ Functional Methods
Atomic read-compute-write map methods including computeIfAbsent, computeIfPresent, merge, and getOrDefault
Java 8 introduced high-performance atomic functional methods that execute read-compute-write passes without requiring redundant map lookups.
Method Overview & Code Patterns
Map<String, Integer> map = new HashMap<>();
// 1. Safe Default Read
int count = map.getOrDefault("apple", 0);
// 2. Put If Absent (Initializes mapping only if absent or null)
map.putIfAbsent("apple", 1);
// 3. Compute If Absent (Premier choice for grouping & graph adjacency lists)
Map<String, List<String>> adj = new HashMap<>();
adj.computeIfAbsent("nodeA", k -> new ArrayList<>()).add("nodeB");
// 4. Compute If Present (Modify existing mapping)
map.computeIfPresent("apple", (k, v) -> v + 1);
// 5. Merge (The gold standard for frequency counting)
map.merge("apple", 1, Integer::sum);Detailed Method Contracts
| Method | When Computed | Return Value | Common DSA Application |
|---|---|---|---|
getOrDefault(k, def) | Always reads | Mapped value or def | Default fallback counter reads |
putIfAbsent(k, v) | Missing or mapped to null | Existing value or null | Idempotent initializations |
computeIfAbsent(k, f) | Key is missing | Newly computed value | Grouping anagrams, adjacency lists |
computeIfPresent(k, f) | Key is present and non-null | Updated value (or null to remove) | Modifying existing counts |
compute(k, f) | Always executes | Final mapped value | Complex recomputation |
merge(k, v, f) | Merges if present; inserts if absent | Final mapped value | Word frequency counters |
Removal via null in compute(): In compute(), computeIfPresent(), and merge(),
returning null from the lambda function removes the key from the map entirely!