HashMap compute(K, BiFunction) in Java

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

Syntax:

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

This method takes two arguments. This method attempts to compute a mapping for the specified 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.HashMap;
import java.util.function.BiFunction;

public class HashMapcompute {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new
HashMap<String, Integer>();

        hashMap.put("Hello", 1);
        hashMap.put("World", 2);

        String key = "123";
        BiFunction<? super String, ? super
Integer, ? extends Integer> remappingFunction =
(a, b) -> Integer.parseInt(a)
                + 12;
        hashMap.compute(key, remappingFunction);

        System.out.println(hashMap);
    }
}

Output:

{123=135, Hello=1, World=2}


No comments:

Post a Comment