Java Utility Library

Java HashMap - computeIfPresent() Method



The java.util.HashMap.computeIfPresent() method is used to update a value in the HashMap, if the specified key is present and non-null. It tries to compute a new mapping given the key and its current mapped value. If the function returns null, the mapping is removed. If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.

Syntax

public V computeIfPresent(
    K key, 
    BiFunction<? super K,? super V,? extends V> remappingFunction
)

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 new value associated with the specified key, or null if none.

Exception

NA.

Example:

In the example below, the java.util.HashMap.computeIfPresent() 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, "Kim");
    MyMap.put(104, "Jo");

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

    //updating value of the specified key using computeIfPresent method
    MyMap.computeIfPresent(103, (k, v) -> "Sam"); 
    MyMap.computeIfPresent(104, (k, v) -> "Lee"); 

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

The output of the above code will be:

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

❮ Java.util - HashMap