computeIfAbsent(K, Function): This method is available in java.util.LinkedHashMap class of Java.
Syntax:
V java.util.HashMap.computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
This method takes two arguments. If the specified key is not already associated with a value attempts to compute its value using the given mapping function and enters it into this map unless null.
Parameters: Two parameters are require for this method.
key: key with which the specified value is to be associated.
mappingFunction: the mapping function to compute a value.
Returns: the current (existing or computed) value associated with the specified key, or null if the computed value is null.
Throws:
ConcurrentModificationException - if it is detected that the mapping function modified this map
Approach
Java
import java.util.LinkedHashMap;import java.util.function.Function;public class LinkedHashMapcomputeIfAbsent {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";Function<? super String, ? extends Integer>mappingFunction = a -> Integer.parseInt(a);linkedHashMap.computeIfAbsent(key, mappingFunction);System.out.println(linkedHashMap);}}
Output:
{Java=1, 1=2}
No comments:
Post a Comment