The computeIfAbsent() in Java computes a given value by using a provided operation function.

Method signature:

The signature for computeIfAbsent() is shown below:

public V computeIfAbsent(K key, Function<? super K, ? extends V> Function)

Methods parameters and return type:

Parameter: It takes a key and a function as a parameter. We perform an operation given in a function on a value of a given key.

Return type: It returns a value of a specific key or null if the mapping is null.

Throws: It throws ConcurrentModificationException.

Example 1:

Here we have computed the 5th value in the hashmap by passing a key and a function in which two values are multiplied.

Source code:

public class Example1 {

    public static void main(String[] args) {

        // create a HashMap and add some values
        HashMap<String, Integer> map = new HashMap<>();
        map.put("1", 100);
        map.put("2", 200);
        map.put("3", 300);
        map.put("4", 400);

        System.out.println("HashMap: " + map.toString());

        map.computeIfAbsent("5", k -> 5 * 25);
        System.out.println("Updated HashMap: "+ map);


HashMap: {1=100, 2=200, 3=300, 4=400}
Updated HashMap: {1=100, 2=200, 3=300, 4=400, 5=125}
BUILD SUCCESSFUL (total time: 1 second)

Example 2:

In this example, we have used string values. We have computed a new string on a key “4.” We have tried again to compute a new string on the 4th key, but as it is already present, so it will not compute again.

Source code:

public class Example2 {
    public static void main(String[] args)
        // create a HashMap and add some values
        HashMap<Integer, String> nameMap = new HashMap<>();
        nameMap.put(1, "Ali");
        nameMap.put(2, "Sara");
        nameMap.put(3, "Virat");
        System.out.println("HashMap: "+ nameMap.toString());
        nameMap.computeIfAbsent(4, k -> "Sameer");
        nameMap.computeIfAbsent(4, k -> "Salman");
        System.out.println("Updated HashMap: " + nameMap);


HashMap: {1=Ali, 2=Sara, 3=Virat}
Updated HashMap: {1=Ali, 2=Sara, 3=Virat, 4=Sameer}
BUILD SUCCESSFUL (total time: 1 second)


Leave A Comment