LinkedHashMap compute(K, BiFunction) in Java

compute(K, BiFunction): This method is available in java.util.LinkedHashMap class of Java.

Syntax:

V java.util.HashMap.compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

This method takes two arguments. This method attempts to compute a mapping for the specified key and its current mapped value.

Note: The remapping function should not modify this map during computation.

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 LinkedHashMapcompute {

    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.compute(key, remappingFunction);

        System.out.println(linkedHashMap);
    }

}

Output:

{Java=1, 1=3}


No comments:

Post a Comment