Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Util Map replace(key, value)

java.util.Map.replace(key, value)

The method Map.replace(key, value) associates the given value with the given key only when the map already contains such key.

Method signature

The signature of the java.util.Map.replace(key, value) method is as follows:

default V replace(K key, V value)

The method is available since Java 8.


  • K key: key for which replace the value,
  • V value: value to associate with the key.

Return value

Returns old value for the key or null there was any.


  • NullPointerException: when the given key or value 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, value):


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);

        String oldval = languages.replace(2, "Clojure");
        System.out.println("Old value: " + oldval);
        System.out.println("No changes: " + languages);

        oldval = languages.replace(1, "Clojure");
        System.out.println("Old value: " + oldval);
        System.out.println("Current map: " + languages);

The above code produces the following output:

Original map: {1=Java}
Old value: null
No changes: {1=Java}
Old value: Java
Current map: {1=Clojure}


Share with the World!