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 Map interface that do the whole update in one call. Every map implementation gets them, and ConcurrentHashMap overrides them to be atomic.

The methods share a convention: a function that returns null means "no value", so it removes the entry or skips the insertion. That makes them compact, but it also means they treat a key mapped to null as absent.

Map default methods
MethodSinceDoesBest for
getOrDefault(k, d)Java 8Returns the value, or d if the key is missing; never insertsReading with a fallback
putIfAbsent(k, v)Java 8Inserts only if missing; returns the existing valueCheap default values
computeIfAbsent(k, f)Java 8Calls f only if missingMultimaps, caches, expensive defaults
computeIfPresent(k, f)Java 8Updates only if present; null removesDecrementing, updating existing entries
compute(k, f)Java 8Always calls f(k, oldOrNull)Updates that handle both cases
merge(k, v, f)Java 8Puts v if missing, else f(old, v); null removesCounting and summing
replaceAll(f), replace(k, old, new)Java 8Rewrites all values; compare-and-set on oneBulk updates
Map.entry(k, v)Java 9An immutable pairBuilding entries and test data

Every example was compiled and run on JDK 21. For thread-safe use of these methods, see ConcurrentHashMap.

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, the appears three times and the word and twice.

Java
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:

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 containsKey version needs an if and three map calls per word.
  • put(w, getOrDefault(w, 0) + 1) handles the missing case with a default but still searches the map twice.
  • merge(w, 1, Integer::sum) says it in one call: insert 1, or add 1 to what is there. It is the idiomatic way to count or sum.
  • getOrDefault for a word that never appeared returns 0 without adding it to the map.

The compute family

Grouping people by city, updating stock and filling a cache show where each of the compute methods fits.

Java
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:

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]}
  • computeIfAbsent(city, k -> new ArrayList<>()).add(name) creates the list the first time a city appears and returns the existing list afterwards, the standard way to build a multimap.
  • computeIfPresent only runs for keys that exist; returning null removed pear when its stock reached zero.
  • compute runs for present and missing keys alike, so its function must handle a null old value, as the kiwi entry did.
  • putIfAbsent(k, expensive(...)) builds its argument every time, even when the key exists, because Java evaluates arguments before the call: the message printed twice. computeIfAbsent calls its function only when needed.

Rules for null values

The new methods use null to mean "no value", and a HashMap can also store null as a real value. The program shows where the two meanings collide.

Java
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:

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
  • putIfAbsent returns null when it inserted and the existing value otherwise, which tells the caller whether its value was used.
  • getOrDefault and computeIfAbsent returning null insert nothing; the map stayed {a=1}.
  • A merge function that returns null removes the key.
  • For a key explicitly mapped to null, getOrDefault returns null, not the default, because the key exists. But putIfAbsent and merge treat that key as absent and replace the null. Avoid storing null values; use a missing key or an explicit placeholder instead.
  • compute on a new key receives null as the old value, so the function must check for it.

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.

Java
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:

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
  • replaceAll raised every price by 10%. The tea price shows the usual floating-point rounding, 3.3000000000000003; use BigDecimal for real money, as the BigDecimal page explains.
  • replace(key, value) only replaces existing keys, so it returned false for a missing one. replace(key, expected, newValue) succeeds only if the current value matches.
  • putAll copies every entry of another map, overwriting existing keys.
  • Map.entry creates a standalone pair. A TreeMap gives firstEntry and lastEntry by key order; see NavigableMap.

Never modify the map inside compute

The function passed to computeIfAbsent, compute or merge runs while the map is in the middle of an update, so it must not change the same map. The most common way to break this rule is a memoized recursive function, where computing one value needs other values from the same cache. The program writes Fibonacci that way, runs it against a HashMap and a ConcurrentHashMap, and then shows the safe version.

Java
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:

Output
HashMap, recursive: ConcurrentModificationException
ConcurrentHashMap, recursive: IllegalStateException: Recursive update
get, compute, then put: fib(90) = 2880067194370816120, cached entries 89
  • Computing fib(30) inside computeIfAbsent calls computeIfAbsent for fib(29), which inserts into the map while the outer call is still running. Since Java 9, HashMap detects this and throws ConcurrentModificationException; in Java 8 the same code could silently corrupt the map.
  • ConcurrentHashMap detects it too and throws IllegalStateException: Recursive update. Older versions could also loop forever. The Javadoc of both methods says the mapping function must not modify the map.
  • The safe pattern is to look up, compute outside any map operation, and then put. fib(90) needed 89 cached entries and returned 2,880,067,194,370,816,120, which fits in a long (fib(93) would not).
  • The same rule applies to merge and compute, and to anything the function calls indirectly, such as a listener or a logging call that reads and writes the same cache.

Changing a map through its views

A map's keySet(), values() and entrySet() are not copies but live views, and most of them can remove entries or change values. That makes some bulk updates one line long. The program removes out-of-stock items, items starting with "f", doubles every quantity, keeps one key, and finally deletes a whole range of a TreeMap.

Java
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:

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}
  • values().removeIf(qty -> qty == 0) removed the pear and plum entries completely: removing a value through the view removes its whole entry.
  • keySet().removeIf removes by key, and keySet().retainAll(Set.of("kiwi")) kept only kiwi. These replace the classic loop with an iterator and iterator.remove(); see removing elements from a map.
  • Map.Entry.setValue during iteration writes straight into the map, which is the cheapest way to change every value; replaceAll does the same in one call.
  • Views can add nothing: keySet().add(...) throws UnsupportedOperationException, because a key alone has no value to store.
  • TreeMap.headMap(2010) is a view of all keys below 2010, so clearing it deleted the 1995 and 2004 entries from the map itself. subMap and tailMap work the same way; see NavigableMap 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.

Java
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):

Output
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 containsKey version, with three lookups per word, was the slowest of the loops. merge needs one hash lookup per word instead of two, and was faster than getOrDefault plus put in this run; across repeated runs on this shared machine the two were sometimes close.
  • computeIfAbsent with a mutable int[1] counter was the fastest: after the first occurrence it does one lookup and increments in place, with no boxing of new Integer values.
  • groupingBy with counting() was the slowest here, since every element passes through the general collector machinery; it returns Long counts and fits naturally at the end of a stream.

The differences are modest. Use merge for clarity, and a mutable counter only in hot paths.

Which method to use

Choosing a Map method
TaskUse
Read with a fallbackgetOrDefault
Count or sum per keymerge(k, 1, Integer::sum)
A list or set per keycomputeIfAbsent(k, x -> new ArrayList<>()).add(v)
Insert a cheap defaultputIfAbsent
Insert an expensive defaultcomputeIfAbsent
Update existing, remove at a limitcomputeIfPresent returning null
Update whether present or notcompute, checking for null
Transform every valuereplaceAll
Same operations across threadsThe same methods on ConcurrentHashMap

Removing entries is covered on removing entries from a map.