Backend Development 9 min read

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

This article introduces the Java 8 Map API enhancements—including getOrDefault, forEach, merge, putIfAbsent, compute, computeIfAbsent, computeIfPresent, and replace—explaining their purpose, showing concise code examples, and demonstrating how they simplify common map‑handling scenarios.

Architecture Digest
Architecture Digest
Architecture Digest
Java 8 Map New Methods: getOrDefault, forEach, merge, putIfAbsent, compute, computeIfAbsent, computeIfPresent, replace

Java's Map interface received several useful methods in JDK 8 that make common map operations more concise and expressive. The article walks through each new method, explains its semantics, and provides side‑by‑side old and new code snippets.

getOrDefault

Attempts to retrieve the value for a given key and returns a supplied default when the key is absent.

private static void testGetOrDefault() {
    Map
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 map entries using a lambda, eliminating the need for an explicit for loop.

private static void testForeach() {
    Map
map = new HashMap<>(4);
    map.put("123", "123");
    // old way
    for (Map.Entry
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 an existing value with a new one using a supplied BiFunction , or inserts the value if the key is absent.

private static void testMerge() {
    Map
cntMap = new HashMap<>(8);
    List
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, avoiding accidental overwrites.

private static void testPutIfAbsent() {
    Map
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

Applies a remapping function to the existing value (or null ) and stores the result, useful for complex updates such as counting occurrences.

private static void testComputer() {
    Map
cntMap = new HashMap<>(8);
    List
list = Arrays.asList("apple", "orange", "banana", "orange");
    for (String item : list) {
        cntMap.compute(item, (k, v) -> {
            if (v == null) {
                v = 1;
            } else {
                v += 1;
            }
            return v;
        });
    }
}

computeIfAbsent

Computes and inserts a value only when the key is missing; otherwise returns the existing value.

private static void testComputerIfAbsent() {
    Map
fibMap = new ConcurrentHashMap<>(16);
    fibMap.put(0, 1);
    fibMap.put(1, 1);
    System.out.println(fib(5, fibMap));
}
private static Integer fib(Integer n, Map
map) {
    return map.computeIfAbsent(n, i -> fib(i - 2, map) + fib(i - 1, map));
}

computeIfPresent

Executes the remapping function only when the key already exists, leaving the map unchanged otherwise.

replace

Replaces the value for a given key if the key is present; does nothing when the key is absent.

Overall, these JDK 8 Map methods enable more readable and compact code for typical map manipulation patterns, reducing boilerplate and potential errors.

backendJavaprogrammingcollectionsJDK8map
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

login 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.