Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Util Map computeIfPresent(Key,BiFunction)

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

The method Map.computeIfPresent(Key, BiFunction) computes a new mapping for the given key and its current mapping value if the value exists and is not null.

Method signature

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

default V computeIfPresent(
    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 new 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.computeIfPresent(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<>();

        // Adding new value:
        nameForId.computeIfPresent(1, (key, oldVal) -> {
            System.out.printf("BiFunction(%d,%s) for new%n",
                    key, oldVal);
            return "Java";
        System.out.println("After add new: " + nameForId);

        // Updating:
        nameForId.put(1, "Java");
        nameForId.computeIfPresent(1, (key, oldVal) -> {
            System.out.printf("BiFunction(%d,%s) update%n",
                    key, oldVal);
            return oldVal.concat("Script");
        System.out.println("After update: " + nameForId);

        // null removes:
        nameForId.computeIfPresent(1, (key, oldVal) -> {
            System.out.printf("BiFunction(%d,%s) -> null%n",
                    key, oldVal);
            return null;
        System.out.println("After null: " + nameForId);

The above code produces the following output:

After add new: {}
BiFunction(1,Java) update
After update: {1=JavaScript}
BiFunction(1,JavaScript) -> null
After null: {}


Share with the World!