Fundamentals 10 min read

JDK 8 New Map Methods: getOrDefault, forEach, merge, putIfAbsent, compute, computeIfAbsent, computeIfPresent, replace

This article introduces the JDK 8 Map API enhancements—including getOrDefault, forEach, merge, putIfAbsent, compute, computeIfAbsent, computeIfPresent, and replace—explaining their usage with clear examples and showing how they simplify common map‑handling patterns in Java.

Architect
Architect
Architect
JDK 8 New Map Methods: getOrDefault, forEach, merge, putIfAbsent, compute, computeIfAbsent, computeIfPresent, replace

Map is a frequently used data structure in Java, and starting with JDK 8 it gained several new default methods that make common operations more concise and expressive.

getOrDefault

The method returns the value associated with a key, or a supplied default value if the key is absent.

private static void testGetOrDefault() {
    Map<String, String> map = new HashMap<>(4);
    map.put("123", "123");
    String key = "key";
    String defaultValue = "defaultValue";

    // old way
    String oldValue = defaultValue;
    if (map.containsKey(key)) {
        oldValue = map.get(key);
    }
    System.out.println("oldValue = " + oldValue);

    // new way
    String newValue = map.getOrDefault(key, defaultValue);
    System.out.println("newValue = " + newValue);
}

forEach

Iterates over the map entries using a lambda expression, eliminating the need for an explicit entry set loop.

private static void testForeach() {
    Map<String, String> map = new HashMap<>(4);
    map.put("123", "123");

    // old way
    for (Map.Entry<String, String> entry : map.entrySet()) {
        System.out.printf("old key = %s, value = %s%n", entry.getKey(), entry.getValue());
    }

    // new way
    map.forEach((key, value) -> System.out.printf("new key = %s, value = %s%n", key, value));
}

merge

Combines a new value with an existing one using a supplied remapping function, or inserts the value if the key is absent.

@Override
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
    if (value == null || remappingFunction == null)
        throw new NullPointerException();
    // ... (implementation omitted for brevity) ...
}

Example – counting occurrences in a list:

private static void testMerge() {
    Map<String, Integer> cntMap = new HashMap<>(8);
    List<String> list = Arrays.asList("apple", "orange", "banana", "orange");

    // old way
    for (String item : list) {
        if (cntMap.containsKey(item)) {
            cntMap.put(item, cntMap.get(item) + 1);
        } else {
            cntMap.put(item, 1);
        }
    }

    // new way
    for (String item : list) {
        cntMap.merge(item, 1, Integer::sum);
    }
}

putIfAbsent

Inserts a key‑value pair only when the key is not already present (or its value is null), avoiding accidental overwrites.

private static void testPutIfAbsent() {
    Map<String, Integer> scoreMap = new HashMap<>(4);
    scoreMap.put("Jim", 88);
    scoreMap.put("Lily", 90);

    // old way
    if (!scoreMap.containsKey("Lily")) {
        scoreMap.put("Lily", 98);
    }

    // new way
    scoreMap.putIfAbsent("Lily", 98);
}

compute

Recomputes the value for a given key using a remapping function that receives the current value (which may be null).

private static void testComputer() {
    Map<String, Integer> cntMap = new HashMap<>(8);
    List<String> list = Arrays.asList("apple", "orange", "banana", "orange");

    // old way
    for (String item : list) {
        if (cntMap.containsKey(item)) {
            cntMap.put(item, cntMap.get(item) + 1);
        } else {
            cntMap.put(item, 1);
        }
    }

    // new way
    for (String item : list) {
        cntMap.compute(item, (k, v) -> v == null ? 1 : v + 1);
    }
}

computeIfAbsent

Computes a value only when the key is missing, then stores and returns it.

private static void testComputerIfAbsent() {
    Map<Integer, Integer> fibMap = new ConcurrentHashMap<>(16);
    fibMap.put(0, 1);
    fibMap.put(1, 1);
    System.out.println(fib(5, fibMap));
}

private static Integer fib(Integer index, Map<Integer, Integer> fibMap) {
    return fibMap.computeIfAbsent(index, i -> fib(i - 2, fibMap) + fib(i - 1, fibMap));
}

computeIfPresent

Executes the remapping function only when the key already exists, updating the value accordingly.

replace

Replaces the value for a key only if the key is present; otherwise it does nothing.

Summary

The JDK 8 Map default methods—getOrDefault, forEach, merge, putIfAbsent, compute, computeIfAbsent, computeIfPresent, and replace—allow developers to write more concise, readable, and less error‑prone code for common map manipulation scenarios.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaprogrammingCollectionsJDK8MAP
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.