Java Utility Library

Java HashMap - computeIfAbsent() Method



The java.util.HashMap.computeIfAbsent() method is used to update a value in the HashMap, if the specified key is not already associated with a value (or is mapped to null). It tries to compute its value using the given mapping function and enters it into this map unless null. If the function returns null no mapping is recorded. If the function itself throws an (unchecked) exception, the exception is rethrown, and no mapping is recorded.

Syntax

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

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

key Specify the key with which the specified value is to be associated.
remappingFunction Specify the function to compute a value.

Return Value

Returns the current (existing or computed) value associated with the specified key, or null if the computed value is null.

Exception

NA.

Example:

In the example below, the java.util.HashMap.computeIfAbsent() method is used to update a value in the given HashMap.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a HashMap
    HashMap<Integer, String> MyMap = new HashMap<Integer, String>();

    //populating the HashMap
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, null);
    MyMap.put(104, "Jo");

    //printing the HashMap
    System.out.println("MyMap contains: " + MyMap);    

    //updating value of the specified key using computeIfAbsent method
    MyMap.computeIfAbsent(103, k -> "Kim"); 
    MyMap.computeIfAbsent(105, k -> "Sam".concat(" Paul")); 

    //printing the HashMap
    System.out.println("MyMap contains: " + MyMap);  
  }
}

The output of the above code will be:

MyMap contains: {101=John, 102=Marry, 103=null, 104=Jo}
MyMap contains: {101=John, 102=Marry, 103=Kim, 104=Jo, 105=Sam Paul}

❮ Java.util - HashMap