Leveraging Java 8 Map Utility Methods

computeIfPresent Method

The computeIfPresent method updates a value if the specified key exists. It passes the key and its current value to a function, which computes and returns a new value.

import java.util.HashMap;
import java.util.Map;

public class MapExample1 {
    public static void main(String[] args) {
        Map<Integer, String> dataMap = new HashMap<>();
        
        dataMap.putIfAbsent(3, "hello");
        
        dataMap.computeIfPresent(3, (key, currentValue) -> {
            System.out.println("Key: " + key);      // Output: 3
            System.out.println("Value: " + currentValue); // Output: hello
            return currentValue + key;               // Returns "hello3"
        });
        
        String result = dataMap.get(3);
        System.out.println(result);  // Output: hello3
    }
}

computeIfAbsent Method

The computeIfAbsent method computes and inserts a value if the key doesn't exist. It takes the key as input and returns the value to be associated with that key.

dataMap.computeIfAbsent(2, (key) -> {
    System.out.println(key);  // Output: 2
    return key + "-value";
});

Method Chaining with computeIfPresent

The computeIfPresent method returns the computed value, allowing for immediate operations on the result.

String updatedValue = dataMap.computeIfPresent(targetKey, (key, existingValue) -> {
    return existingValue + "-modified";
});

merge Method

The merge method combines values for existing keys or inserts new key-value pairs. If the key exists, it applies a merging function to combine the old and new values.

import java.util.HashMap;
import java.util.Map;

public class MergeExample {
    public static void main(String[] args) {
        Map<Integer, String> sampleMap = new HashMap<>();
        
        // First merge - key doesn't exist
        sampleMap.merge(5, "initial", (oldVal, newVal) -> {
            System.out.println("This won't execute");
            return oldVal.concat(newVal);
        });
        
        System.out.println(sampleMap.get(5)); // Output: initial
        
        // Second merge - key exists
        sampleMap.merge(5, "-updated", (current, addition) -> {
            System.out.println("Current: " + current);   // Output: initial
            System.out.println("Addition: " + addition); // Output: -updated
            return current + addition;
        });
        
        System.out.println(sampleMap.get(5)); // Output: initial-updated
    }
}

The merge method inserts the key-value pair if the key is absent. For existing keys, it applies the merge functon to combine values.

Tags: java java8 Map Collections Utilities

Posted on Tue, 27 Oct 2026 16:08:38 +0000 by Wildhalf