Which Map methods added in Java 8 should every developer know?

Java 8 added default methods to Map that replace common multi-line patterns with a single call: getOrDefault(), putIfAbsent(), computeIfAbsent(), computeIfPresent(), compute(), merge(), forEach(), replaceAll() and removeIf() on the entry set. They make code shorter and, on ConcurrentHashMap, atomic.

Key Points: • getOrDefault(key, default) avoids null checks when a key is missing. • computeIfAbsent(key, k -> new ArrayList<>()) creates a value only when needed. It's ideal for grouping into Map<K, List<V>>. • merge(key, 1, Integer::sum) is the shortest way to count occurrences. • putIfAbsent() adds only when the key is missing. • compute() and computeIfPresent() update existing values. Returning null from the function removes the entry. • map.entrySet().removeIf(e -> ...) removes entries matching a condition.

Code Example:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Java8MapMethods {

    public static void main(String[] args) {
        String[] words = {"java", "spring", "java", "kafka", "java", "spring"};

        // Counting
        Map<String, Integer> counts = new TreeMap<>();
        for (String w : words) counts.merge(w, 1, Integer::sum);
        System.out.println("Counts: " + counts);

        // Grouping by first letter
        Map<Character, List<String>> byLetter = new TreeMap<>();
        for (String w : words) byLetter.computeIfAbsent(w.charAt(0), k -> new ArrayList<>()).add(w);
        System.out.println("Grouped: " + byLetter);

        System.out.println("Count of docker: " + counts.getOrDefault("docker", 0));

        counts.computeIfPresent("kafka", (k, v) -> v + 10);
        counts.replaceAll((k, v) -> v * 2);
        counts.entrySet().removeIf(e -> e.getValue() < 5);
        System.out.println("After updates: " + counts);
    }
}

Output:

Counts: {java=3, kafka=1, spring=2} Grouped: {j=[java, java, java], k=[kafka], s=[spring, spring]} Count of docker: 0 After updates: {java=6, kafka=22}

Good to Know: On a ConcurrentHashMap these methods are atomic, which makes them the correct way to update shared counters or caches from several threads. A common bug is calling map.put(key, map.get(key) + 1) from multiple threads, which can lose updates. merge() avoids that.

Interview Tip: A concise interview answer is:

"Java 8 added getOrDefault, putIfAbsent, computeIfAbsent, computeIfPresent, compute, merge, forEach and replaceAll to Map. I use merge(key, 1, Integer::sum) for counting and computeIfAbsent(key, k -> new ArrayList<>()).add(value) for grouping. On ConcurrentHashMap they're atomic, so they're also the safe way to update shared maps."

Previous question: What are the most useful methods of the Collections utility class?

Next question: Why is ArrayDeque preferred over Stack and LinkedList for stacks and queues?

More Java Collections interview questions

All Java Collections questions