Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Util Map compute(Key, BiFunction)

java.util.Map.compute(Key, BiFunction)

The method Map.compute(Key, BiFunction) returns the new value associated with the specified key. The value is computed using the given function.

Method signature

The signature of the java.util.Map.compute(Key, BiFunction) method is as follows:

default V compute(
    K key,
    BiFunction<? super K,? super V,? extends V> remappingFunction

The method is available since Java 8.


  • K key: key with which associate the value,
  • BiFunction remappingFunction: function to compute the value.

Return value

The new value associated with the specified key, or null if none.


  • NullPointerException: when remappingFunction is null or if the specified key is null and this map does not support null keys,
  • UnsupportedOperationException: if the put operation is not supported by this map (optional)
  • ClassCastException: if the class of the specified key or value prevents it from being stored in this map (optional)

Example usage

In the following code we use java.util.Map.compute(Key, BiFunction):


import java.util.HashMap;
import java.util.Map;

public class MapExamples {

    public static void main(String[] args) {
        Map<Integer,String> nameForId = new HashMap<>();
        nameForId.put(1, "Java");
        nameForId.put(2, "Clojure");
        System.out.println("Original map: " + nameForId);

        // recompute the values:
        nameForId.compute(1, (key, oldVal) -> oldVal.concat("Script"));
        nameForId.compute(2, (key, oldVal) -> oldVal.concat("Script"));
        System.out.println("Recomputed map: " + nameForId);

        // return "null" to remove value:
        nameForId.compute(1, (key, oldVal) -> null);
        // null for nothing does nothing:
        nameForId.compute(3, (key, oldVal) -> null);
        System.out.println("After null: " + nameForId);

        // unchecked exceptions are rethrown:
        try {
            nameForId.compute(1, (key, oldVal) -> {
                throw new RuntimeException("Drakaris!");
        } catch (RuntimeException e) {
            System.out.println("Rethrown: " + e.getMessage());
        System.out.println("Map after exception: " + nameForId);

The above code produces the following output:

Original map: {1=Java, 2=Clojure}
Recomputed map: {1=JavaScript, 2=ClojureScript}
After null: {2=ClojureScript}
Rethrown: Drakaris!
Map after exception: {2=ClojureScript}


Share with the World!