Advanced Map Methods
Java 8 added a set of default methods to Map that replace the check-then-put code most programs used to write: getOrDefault, putIfAbsent, merge, compute, computeIfAbsent, computeIfPresent and replaceAll. This page explains what each does, shows them counting, grouping and caching, spells out their surprising rules for null values, and measures the counting idioms.
Contents
From check-then-put to one call
Before Java 8, updating a map usually took two or three calls: check whether the key exists, read the old value, put a new one. Each call searches the map again, the code is longer, and on a shared map another thread can slip in between the calls. Java 8 added default methods to the MapConcurrentHashMap
The methods share a convention: a function that returns nullnull
| Method | Since | Does | Best for |
|---|---|---|---|
getOrDefault(k, d) | Java 8 | Returns the value, or d | Reading with a fallback |
putIfAbsent(k, v) | Java 8 | Inserts only if missing; returns the existing value | Cheap default values |
computeIfAbsent(k, f) | Java 8 | Calls f | Multimaps, caches, expensive defaults |
computeIfPresent(k, f) | Java 8 | Updates only if present; null | Decrementing, updating existing entries |
compute(k, f) | Java 8 | Always calls f(k, oldOrNull) | Updates that handle both cases |
merge(k, v, f) | Java 8 | Puts vf(old, v)null | Counting and summing |
replaceAll(f)replace(k, old, new) | Java 8 | Rewrites all values; compare-and-set on one | Bulk updates |
Map.entry(k, v) | Java 9 | An immutable pair | Building entries and test data |
Every example was compiled and run on JDK 21. For thread-safe use of these methods, see
Counting: four versions of the same idea
Counting words is the standard example, because each word either starts a new count or adds to an existing one. In the test sentence, theand
import java.util.Map;
import java.util.TreeMap;
public class DefaultsAndCounting {
public static void main(String[] args) {
String text = "the cat and the hat and the bat";
// Old style: check, then put
Map<String, Integer> oldWay = new TreeMap<>();
for (String w : text.split(" ")) {
if (oldWay.containsKey(w)) {
oldWay.put(w, oldWay.get(w) + 1);
} else {
oldWay.put(w, 1);
}
}
System.out.println("containsKey/put: " + oldWay);
// getOrDefault: no null check needed
Map<String, Integer> withDefault = new TreeMap<>();
for (String w : text.split(" ")) {
withDefault.put(w, withDefault.getOrDefault(w, 0) + 1);
}
System.out.println("getOrDefault: " + withDefault);
// merge: insert 1, or combine with the existing value
Map<String, Integer> merged = new TreeMap<>();
for (String w : text.split(" ")) {
merged.merge(w, 1, Integer::sum);
}
System.out.println("merge: " + merged);
System.out.println("count of 'dog': " + merged.getOrDefault("dog", 0));
}
}
Output:
containsKey/put: {and=2, bat=1, cat=1, hat=1, the=3}
getOrDefault: {and=2, bat=1, cat=1, hat=1, the=3}
merge: {and=2, bat=1, cat=1, hat=1, the=3}
count of 'dog': 0
- All three versions give the same counts. The
version needs ancontainsKey and three map calls per word.if handles the missing case with a default but still searches the map twice.put(w, getOrDefault(w, 0) + 1) says it in one call: insert 1, or add 1 to what is there. It is the idiomatic way to count or sum.merge(w, 1, Integer::sum) for a word that never appeared returns 0 without adding it to the map.getOrDefault
The compute family
Grouping people by city, updating stock and filling a cache show where each of the compute methods fits.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class ComputeFamily {
record Person(String name, String city) {
}
public static void main(String[] args) {
// computeIfAbsent: create the value the first time a key is seen (a multimap)
Map<String, List<String>> byCity = new TreeMap<>();
List<Person> people = List.of(
new Person("ana", "Lima"), new Person("erik", "Oslo"), new Person("luis", "Lima"));
for (Person p : people) {
byCity.computeIfAbsent(p.city(), city -> new ArrayList<>()).add(p.name());
}
System.out.println("computeIfAbsent: " + byCity);
// computeIfPresent: change only existing keys; returning null removes the key
Map<String, Integer> stock = new TreeMap<>(Map.of("apple", 3, "pear", 1));
stock.computeIfPresent("apple", (k, v) -> v - 1);
stock.computeIfPresent("pear", (k, v) -> v - 1 == 0 ? null : v - 1);
stock.computeIfPresent("kiwi", (k, v) -> v - 1); // absent: nothing happens
System.out.println("computeIfPresent: " + stock);
// compute: always runs; the old value is null when the key is absent
stock.compute("kiwi", (k, v) -> v == null ? 10 : v + 10);
stock.compute("kiwi", (k, v) -> v == null ? 10 : v + 10);
System.out.println("compute twice: " + stock);
// putIfAbsent vs computeIfAbsent: the first always builds its argument
Map<String, List<String>> cache = new TreeMap<>();
cache.putIfAbsent("k", expensive("putIfAbsent"));
cache.putIfAbsent("k", expensive("putIfAbsent again"));
cache.computeIfAbsent("k", key -> expensive("computeIfAbsent"));
System.out.println("cache: " + cache);
}
static List<String> expensive(String caller) {
System.out.println(" building a value for " + caller);
return new ArrayList<>(List.of(caller));
}
}
Output:
computeIfAbsent: {Lima=[ana, luis], Oslo=[erik]}
computeIfPresent: {apple=2}
compute twice: {apple=2, kiwi=20}
building a value for putIfAbsent
building a value for putIfAbsent again
cache: {k=[putIfAbsent]}
creates the list the first time a city appears and returns the existing list afterwards, the standard way to build a multimap.computeIfAbsent(city, k -> new ArrayList<>()).add(name) only runs for keys that exist; returningcomputeIfPresent removednull when its stock reached zero.pear runs for present and missing keys alike, so its function must handle acompute old value, as the kiwi entry did.null builds its argument every time, even when the key exists, because Java evaluates arguments before the call: the message printed twice.putIfAbsent(k, expensive(...)) calls its function only when needed.computeIfAbsent
Rules for null values
The new methods use nullHashMapnull
import java.util.HashMap;
import java.util.Map;
public class NullSemantics {
public static void main(String[] args) {
Map<String, Integer> m = new HashMap<>();
// putIfAbsent returns the existing value, or null if it inserted
System.out.println("putIfAbsent(a, 1) -> " + m.putIfAbsent("a", 1));
System.out.println("putIfAbsent(a, 2) -> " + m.putIfAbsent("a", 2) + " " + m);
// getOrDefault never inserts
System.out.println("getOrDefault(b, 0) -> " + m.getOrDefault("b", 0) + " " + m);
// computeIfAbsent: a null result inserts nothing
System.out.println("computeIfAbsent(b, null) -> " + m.computeIfAbsent("b", k -> null)
+ " " + m);
// merge: returning null removes the key
m.merge("a", 1, (old, add) -> null);
System.out.println("merge returning null removed a: " + m);
// A key mapped to null counts as absent for these methods
m.put("c", null);
System.out.println("map with c=null: " + m + ", containsKey(c) " + m.containsKey("c"));
System.out.println("getOrDefault(c, 9) -> " + m.getOrDefault("c", 9)
+ " (the key exists, so the default is not used)");
m.putIfAbsent("c", 5);
System.out.println("putIfAbsent(c, 5) replaced the null: " + m);
m.put("d", null);
m.merge("d", 7, Integer::sum);
System.out.println("merge on a null value just stores 7: " + m);
// compute sees null for a missing key and must handle it
m.compute("e", (k, v) -> v == null ? 1 : v + 1);
m.compute("e", (k, v) -> v == null ? 1 : v + 1);
System.out.println("compute twice on a new key: e=" + m.get("e"));
}
}
Output:
putIfAbsent(a, 1) -> null
putIfAbsent(a, 2) -> 1 {a=1}
getOrDefault(b, 0) -> 0 {a=1}
computeIfAbsent(b, null) -> null {a=1}
merge returning null removed a: {}
map with c=null: {c=null}, containsKey(c) true
getOrDefault(c, 9) -> null (the key exists, so the default is not used)
putIfAbsent(c, 5) replaced the null: {c=5}
merge on a null value just stores 7: {c=5, d=7}
compute twice on a new key: e=2
returnsputIfAbsent when it inserted and the existing value otherwise, which tells the caller whether its value was used.null andgetOrDefault returningcomputeIfAbsent insert nothing; the map stayednull .{a=1}- A merge function that returns
removes the key.null - For a key explicitly mapped to
,null returnsgetOrDefault , not the default, because the key exists. Butnull andputIfAbsent treat that key as absent and replace themerge . Avoid storingnull values; use a missing key or an explicit placeholder instead.null on a new key receivescompute as the old value, so the function must check for it.null
Bulk updates, replace and ordered access
A small price list is updated in bulk, conditionally and from another map, and then read from both ends with a sorted map.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class BulkAndViews {
public static void main(String[] args) {
Map<String, Double> prices = new LinkedHashMap<>();
prices.put("tea", 3.0);
prices.put("cake", 4.5);
prices.put("juice", 2.0);
// replaceAll: new value from key and old value, for every entry
prices.replaceAll((item, p) -> item.equals("cake") ? p : p * 1.1);
System.out.println("replaceAll: " + prices);
// replace only if the key exists; replace(key, old, new) only if the value matches
prices.replace("coffee", 3.5);
System.out.println("replace missing key: " + prices.containsKey("coffee"));
System.out.println("replace(cake, 4.5, 5.0): " + prices.replace("cake", 4.5, 5.0));
// putAll merges another map in, overwriting equal keys
prices.putAll(Map.of("juice", 2.5, "water", 1.0));
System.out.println("putAll: " + new TreeMap<>(prices));
// Map.entry creates a standalone, immutable key-value pair
Map.Entry<String, Double> special = Map.entry("scone", 2.8);
System.out.println("entry: " + special.getKey() + " at " + special.getValue());
// Java 21: sequenced maps know their first and last entries
LinkedHashMap<String, Double> ordered = new LinkedHashMap<>(prices);
System.out.println("firstEntry: " + ordered.firstEntry());
System.out.println("lastEntry: " + ordered.lastEntry());
}
}
Output:
replaceAll: {tea=3.3000000000000003, cake=4.5, juice=2.2}
replace missing key: false
replace(cake, 4.5, 5.0): true
putAll: {cake=5.0, juice=2.5, tea=3.3000000000000003, water=1.0}
entry: scone at 2.8
firstEntry: tea=3.3000000000000003
lastEntry: water=1.0
raised every price by 10%. The tea price shows the usual floating-point rounding, 3.3000000000000003; usereplaceAll for real money, as theBigDecimalBigDecimal page explains. only replaces existing keys, so it returnedreplace(key, value) for a missing one.false succeeds only if the current value matches.replace(key, expected, newValue) copies every entry of another map, overwriting existing keys.putAll creates a standalone pair. AMap.entry givesTreeMap andfirstEntry by key order; seelastEntryNavigableMap .
Never modify the map inside compute
The function passed to computeIfAbsentcomputemergeHashMapConcurrentHashMap
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class RecursiveCompute {
static Map<Integer, Long> memo;
// Memoized Fibonacci that calls itself from inside computeIfAbsent: a classic mistake
static long fibCompute(int n) {
if (n < 2) {
return n;
}
return memo.computeIfAbsent(n, k -> fibCompute(k - 1) + fibCompute(k - 2));
}
// The safe version: compute first, then store
static long fibSafe(int n) {
if (n < 2) {
return n;
}
Long cached = memo.get(n);
if (cached != null) {
return cached;
}
long value = fibSafe(n - 1) + fibSafe(n - 2);
memo.put(n, value);
return value;
}
public static void main(String[] args) {
memo = new HashMap<>();
try {
System.out.println("HashMap, recursive: " + fibCompute(30));
} catch (ConcurrentModificationException e) {
System.out.println("HashMap, recursive: ConcurrentModificationException");
}
memo = new ConcurrentHashMap<>();
try {
System.out.println("ConcurrentHashMap, recursive: " + fibCompute(30));
} catch (IllegalStateException e) {
System.out.println("ConcurrentHashMap, recursive: IllegalStateException: "
+ e.getMessage());
}
memo = new HashMap<>();
System.out.println("get, compute, then put: fib(90) = " + fibSafe(90)
+ ", cached entries " + memo.size());
}
}
Output:
HashMap, recursive: ConcurrentModificationException
ConcurrentHashMap, recursive: IllegalStateException: Recursive update
get, compute, then put: fib(90) = 2880067194370816120, cached entries 89
- Computing fib(30) inside
callscomputeIfAbsent for fib(29), which inserts into the map while the outer call is still running. Since Java 9,computeIfAbsent detects this and throwsHashMap ; in Java 8 the same code could silently corrupt the map.ConcurrentModificationException detects it too and throwsConcurrentHashMap . Older versions could also loop forever. The Javadoc of both methods says the mapping function must not modify the map.IllegalStateException: Recursive update- The safe pattern is to look up, compute outside any map operation, and then
. fib(90) needed 89 cached entries and returned 2,880,067,194,370,816,120, which fits in aput (fib(93) would not).long - The same rule applies to
andmerge , and to anything the function calls indirectly, such as a listener or a logging call that reads and writes the same cache.compute
Changing a map through its views
A map's keySet()values()entrySet()TreeMap
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class WritableViews {
public static void main(String[] args) {
Map<String, Integer> stock = new LinkedHashMap<>();
stock.put("apple", 12);
stock.put("pear", 0);
stock.put("kiwi", 7);
stock.put("plum", 0);
stock.put("fig", 3);
// values().removeIf removes whole entries whose value matches
stock.values().removeIf(qty -> qty == 0);
System.out.println("after values().removeIf(qty == 0): " + stock);
// keySet().removeIf removes by key
stock.keySet().removeIf(name -> name.startsWith("f"));
System.out.println("after keySet().removeIf(starts with f): " + stock);
// entrySet: setValue writes through to the map
for (Map.Entry<String, Integer> e : stock.entrySet()) {
e.setValue(e.getValue() * 2);
}
System.out.println("after setValue(doubled): " + stock);
// retainAll on the key set keeps only the listed keys
stock.keySet().retainAll(Set.of("kiwi"));
System.out.println("after keySet().retainAll({kiwi}): " + stock);
// Views of a TreeMap: headMap and tailMap write through too
TreeMap<Integer, String> byYear = new TreeMap<>(Map.of(1995, "Java 1.0", 2004, "Java 5",
2014, "Java 8", 2018, "Java 11", 2021, "Java 17", 2023, "Java 21"));
byYear.headMap(2010).clear(); // delete everything before 2010
System.out.println("after headMap(2010).clear(): " + byYear);
}
}
Output:
after values().removeIf(qty == 0): {apple=12, kiwi=7, fig=3}
after keySet().removeIf(starts with f): {apple=12, kiwi=7}
after setValue(doubled): {apple=24, kiwi=14}
after keySet().retainAll({kiwi}): {kiwi=14}
after headMap(2010).clear(): {2014=Java 8, 2018=Java 11, 2021=Java 17, 2023=Java 21}
removed the pear and plum entries completely: removing a value through the view removes its whole entry.values().removeIf(qty -> qty == 0) removes by key, andkeySet().removeIf kept only kiwi. These replace the classic loop with an iterator andkeySet().retainAll(Set.of("kiwi")) ; seeiterator.remove()removing elements from a map . during iteration writes straight into the map, which is the cheapest way to change every value;Map.Entry.setValue does the same in one call.replaceAll- Views can add nothing:
throwskeySet().add(...) , because a key alone has no value to store.UnsupportedOperationException is a view of all keys below 2010, so clearing it deleted the 1995 and 2004 entries from the map itself.TreeMap.headMap(2010) andsubMap work the same way; seetailMapNavigableMap and NavigableSet .
How fast is each counting idiom?
The program counts two million words drawn from 5,000 distinct values with five idioms, keeping the fastest of three runs.
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.Arrays;
public class CountingSpeed {
public static void main(String[] args) {
Random random = new Random(4);
String[] words = new String[2000000];
for (int i = 0; i < words.length; i++) {
words[i] = "w" + random.nextInt(5000);
}
System.out.printf("count %,d words with 5,000 distinct values%n", words.length);
time("containsKey + get + put", words, w -> {
Map<String, Integer> m = new HashMap<>();
for (String s : w) {
if (m.containsKey(s)) {
m.put(s, m.get(s) + 1);
} else {
m.put(s, 1);
}
}
return m;
});
time("getOrDefault + put", words, w -> {
Map<String, Integer> m = new HashMap<>();
for (String s : w) {
m.put(s, m.getOrDefault(s, 0) + 1);
}
return m;
});
time("merge(s, 1, Integer::sum)", words, w -> {
Map<String, Integer> m = new HashMap<>();
for (String s : w) {
m.merge(s, 1, Integer::sum);
}
return m;
});
time("computeIfAbsent + int[]", words, w -> {
Map<String, int[]> m = new HashMap<>();
for (String s : w) {
m.computeIfAbsent(s, k -> new int[1])[0]++;
}
return m;
});
time("groupingBy counting", words, w -> Arrays.stream(w)
.collect(Collectors.groupingBy(s -> s, Collectors.counting())));
}
// Best of 3 runs
static void time(String name, String[] words, Function<String[], Map<String, ?>> f) {
long best = Long.MAX_VALUE;
int keys = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
keys = f.apply(words).size();
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-28s %6.1f ms (%,d keys)%n", name, best / 1e6, keys);
}
}
Output (rough timings, two CPUs, Linux, JDK 21):
count 2,000,000 words with 5,000 distinct values
containsKey + get + put 80.3 ms (5,000 keys)
getOrDefault + put 71.1 ms (5,000 keys)
merge(s, 1, Integer::sum) 50.8 ms (5,000 keys)
computeIfAbsent + int[] 44.9 ms (5,000 keys)
groupingBy counting 99.7 ms (5,000 keys)
- The
version, with three lookups per word, was the slowest of the loops.containsKey needs one hash lookup per word instead of two, and was faster thanmerge plusgetOrDefault in this run; across repeated runs on this shared machine the two were sometimes close.put with a mutablecomputeIfAbsent counter was the fastest: after the first occurrence it does one lookup and increments in place, with no boxing of newint[1] values.Integer withgroupingBy was the slowest here, since every element passes through the general collector machinery; it returnscounting() counts and fits naturally at the end of a stream.Long
The differences are modest. Use merge
Which method to use
| Task | Use |
|---|---|
| Read with a fallback | getOrDefault |
| Count or sum per key | merge(k, 1, Integer::sum) |
| A list or set per key | computeIfAbsent(k, x -> new ArrayList<>()).add(v) |
| Insert a cheap default | putIfAbsent |
| Insert an expensive default | computeIfAbsent |
| Update existing, remove at a limit | computeIfPresentnull |
| Update whether present or not | computenull |
| Transform every value | replaceAll |
| Same operations across threads | The same methods on ConcurrentHashMap |
Removing entries is covered on