Open In App

HashMap computeIfPresent(key, BiFunction) method in Java with Examples

The computeIfPresent(Key, BiFunction) method of HashMap class which allows you to compute value of a mapping for specified key if key is already associated with a value (or is mapped to null).

Syntax:



public Object computeIfPresent(Object key,
                  BiFunction remappingFunction)

Parameters: This method accepts two parameters:

Returns: This method returns new remapped value associated with the specified key, or null if mapping returns null.



Below programs illustrate the computeIfPresent(Key, BiFunction) method:

Example 1: This example demonstrates the case when the key is not in the hashmap.




// Java program to demonstrate
// computeIfPresent(Key, BiFunction) method.
  
import java.util.concurrent.*;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Create a HashMap and add some values
        HashMap<String, Integer> wordCount = new HashMap<>();
        wordCount.put("Geeks", 1);
        wordCount.put("for", 2);
        wordCount.put("geeks", 3);
  
        // print HashMap details
        System.out.println("Hashmap before operation :\n "
                           + wordCount);
  
        // provide new value for keys which is present
        // using computeIfPresent method
        wordCount.computeIfPresent("Geek",
                                   (key, val) -> val + 100);
  
        // print new mapping
        System.out.println("HashMap after operation :\n "
                           + wordCount);
    }
}

Output:
Hashmap before operation :
 {geeks=3, Geeks=1, for=2}
HashMap after operation :
 {geeks=3, Geeks=1, for=2}

Example 2: This example demonstrates the case when the key is present in the hashmap.




// Java program to demonstrate
// computeIfPresent(Key, BiFunction) method.
  
import java.util.concurrent.*;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Create a HashMap and add some values
        HashMap<String, Integer> wordCount = new HashMap<>();
        wordCount.put("Geeks", 1);
        wordCount.put("for", 2);
        wordCount.put("geeks", 3);
  
        // print HashMap details
        System.out.println("Hashmap before operation :\n "
                           + wordCount);
  
        // provide new value for keys which is present
        // using computeIfPresent method
        wordCount.computeIfPresent("for",
                                   (key, val) -> val + 1);
  
        // print new mapping
        System.out.println("HashMap after operation :\n "
                           + wordCount);
    }
}

Output:
Hashmap before operation :
 {geeks=3, Geeks=1, for=2}
HashMap after operation :
 {geeks=3, Geeks=1, for=3}

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#computeIfPresent-K-java.util.function.BiFunction-


Article Tags :