Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Util Map replace(key, oldValue, newValue)

java.util.Map.replace(key, oldValue, newValue)

The method Map.replace(key, oldValue, newValue) replaces the value associated with the given key only if it is currently mapped to the oldValue.

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.replace(key, oldValue, newValue) method is as follows:

default boolean replace(K key, V oldValue, V newValue)

The method is available since Java 8.


  • K key: key for which replace the value
  • V oldValue: value expected to be associated with the key
  • V newValue: value to associate with the key

Return value

Returns true when the value was replaced.


  • NullPointerException: when the given key or newValue is null and the map doesn’t allow null keys or values (optional)
  • UnsupportedOperationException: if the put operation is not supported by this map (optional)
  • ClassCastException: if the key or value is of not acceptable by this map (optional)
  • IllegalArgumentException: when some property of the given key or value prevents it from being stored in this map

Example usage

In the following code we use java.util.Map.replace(key, oldValue, newValue):


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

public class MapExamples {

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

        boolean replaced = languages.replace(1, "Clojure", "Python");
        System.out.printf("Replaced: %b, the map: %s%n",
                replaced, languages);

        replaced = languages.replace(1, "Java", "Python");
        System.out.printf("Replaced: %b, the map: %s%n",
                replaced, languages);

The above code produces the following output:

Original map: {1=Java}
Replaced: false, the map: {1=Java}
Replaced: true, the map: {1=Python}


Share with the World!