Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Util Map replaceAll(BiFunction)


The method Map.replaceAll(BiFunction) replaces each value with the result of applying the given function on the corresponding entry. Rethrows exceptions thrown by the replacement function.

Note that this default method does not make any guarantees about thread-safety. This is left to implementations and should be clearly documented by them.

Method signature

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

default void replaceAll(
        BiFunction<? super K,? super V,? extends V> function)

The method is available since Java 8.


  • BiConsumer<? super K, ? super V, ? extends V> action – action to be performed on each entry.

Return value

It replaces values in place and the method returns nothing.


  • ClassCastException: if the replacement class is of type not acceptable by this map
  • ConcurrentModificationException: when an entry is found to be removed during iteration.
  • IllegalArgumentException: when some property of the replacement value prevents it from being stored in this map (optional)
  • NullPointerException: when the given function or newValue is null and the map doesn’t allow null keys or values (optional)
  • UnsupportedOperationException: if the set operation is not supported by this map (optional)

Example usage

In the following code we use java.util.Map.replaceAll(BiFunction):


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

public class MapExamples {

    public static void main(String[] args) {
        Map<Integer,Integer> numbers = new HashMap<>();
        for (int i = 1; i <= 10; ++i) {
            numbers.put(i, i);
        System.out.println("Original: " + numbers);

        numbers.replaceAll((key, oldValue) -> oldValue * oldValue);
        System.out.println("Squared: " + numbers);

The above code produces the following output:

Original: {1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10}
Squared: {1=1, 2=4, 3=9, 4=16, 5=25, 6=36, 7=49, 8=64, 9=81, 10=100}


Share with the World!