Attic
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

ModernMapMethods.java
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

MethodWhen ComputedReturn ValueCommon DSA Application
getOrDefault(k, def)Always readsMapped value or defDefault fallback counter reads
putIfAbsent(k, v)Missing or mapped to nullExisting value or nullIdempotent initializations
computeIfAbsent(k, f)Key is missingNewly computed valueGrouping anagrams, adjacency lists
computeIfPresent(k, f)Key is present and non-nullUpdated value (or null to remove)Modifying existing counts
compute(k, f)Always executesFinal mapped valueComplex recomputation
merge(k, v, f)Merges if present; inserts if absentFinal mapped valueWord 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!

On this page