computeIfPresent(K, BiFunction): This method is available in java.util.LinkedHashMap class of Java.
Syntax:
V java.util.HashMap.computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
This method takes two arguments. If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
Parameters: Two parameters are required for this method.
key: key with which the specified value is to be associated.
remappingFunction: the remapping function to compute a value.
Returns: the new value associated with the specified key, or null if none.
Throws:
ConcurrentModificationException - if it is detected that the remapping function modified this map
Approach
Java
import java.util.LinkedHashMap;import java.util.function.BiFunction;public class LinkedHashMapcomputeIfPresent {public static void main(String args[]) {LinkedHashMap<String, Integer> linkedHashMap =new LinkedHashMap<String, Integer>();linkedHashMap.put("Java", 1);linkedHashMap.put("1", 2);String key = "1";BiFunction<? super String, ? super Integer,? extends Integer> remappingFunction = (a,b) -> (Integer.parseInt(a) + b);linkedHashMap.computeIfPresent(key, remappingFunction);System.out.println(linkedHashMap);}}
Output:
{Java=1, 1=3}
No comments:
Post a Comment