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).
- If mapping function of this method returns null, the mapping is removed.
- If the remapping function throws an exception, the exception is rethrown, and the mapping is left unchanged.
- During computation, modification this map using this method is not allowed.
Syntax:
public Object computeIfPresent(Object key,
BiFunction remappingFunction)
Parameters: This method accepts two parameters:
- key: key with which the value is to be associated.
- remappingFunction: function to do the operation on value.
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.
import java.util.concurrent.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashMap<String, Integer> wordCount = new HashMap<>();
wordCount.put( "Geeks" , 1 );
wordCount.put( "for" , 2 );
wordCount.put( "geeks" , 3 );
System.out.println( "Hashmap before operation :\n "
+ wordCount);
wordCount.computeIfPresent( "Geek" ,
(key, val) -> val + 100 );
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.
import java.util.concurrent.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashMap<String, Integer> wordCount = new HashMap<>();
wordCount.put( "Geeks" , 1 );
wordCount.put( "for" , 2 );
wordCount.put( "geeks" , 3 );
System.out.println( "Hashmap before operation :\n "
+ wordCount);
wordCount.computeIfPresent( "for" ,
(key, val) -> val + 1 );
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-