Java HashMap replace() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

In Java, replace(key, value) sets a new value for key only if the key is already in the map, and returns the old value. For a missing key it does nothing and returns null; unlike put, it never adds a mapping.

The overload replace(key, oldValue, newValue) changes the value only if the key is currently mapped to oldValue (compared with equals) and returns true or false. It works like a compare-and-set.

An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety. Both replace overloads were added in Java 8 as default methods of Map; HashMap overrides them.

Syntax

Two overloads: unconditional, and conditional on the current value.

Java
Map<String, Integer> prices = new HashMap<>();
prices.put("apple", 40);
Integer old = prices.replace("apple", 45);         // 40
boolean ok = prices.replace("apple", 45, 50);      // true
Integer none = prices.replace("kiwi", 30);         // null, not added
CallWhat it does
map.replace(k, v)Replaces if k exists; returns the old value or null.
map.replace(k, old, v)Replaces only if k maps to old; returns a boolean.
map.put(k, v)Replaces or adds.
map.replaceAll(f)Replaces every value with a function.

For the one-argument check, a key mapped to null still counts as present, so its null is replaced.

Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public V replace(K key, V value)
public boolean replace(K key, V oldValue, V newValue)

// Default methods in Map<K, V>, overridden by HashMap

Parameters

ParameterDescription
key (K)The key whose value should change.
value / newValue (V)The new value. May be null in a HashMap.
oldValue (V)Three-argument form only: the value the key must currently have.

Return Value

Return ValueDescription
V (two arguments)The previous value, or null if the key was missing (or mapped to null).
boolean (three arguments)true if the value was replaced.

Compare with Similar Methods

Updating existing values:

MethodHow it differs
put(k, v)Adds the key if it is missing.
replaceAll(f)Updates every mapping in one call.
computeIfPresent(k, f)Computes the new value from the old one.
remove(k, v)The conditional delete counterpart.

Java Examples

Example 1 — Update a Price, Ignore a Missing Item

Replace the price of an existing fruit, try a missing one, and compare with put.

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

public class HashMapReplaceDemo {
    public static void main(String[] args) {
        Map<String, Integer> prices = new HashMap<>();
        prices.put("apple", 40);
        prices.put("mango", 90);

        Integer oldApple = prices.replace("apple", 45);
        Integer oldKiwi = prices.replace("kiwi", 30);

        System.out.println("apple was " + oldApple + ", now " + prices.get("apple"));
        System.out.println("kiwi replace returned " + oldKiwi + ", kiwi added? " + prices.containsKey("kiwi"));

        prices.put("kiwi", 30);
        System.out.println("put adds it: " + prices.get("kiwi") + ", size " + prices.size());
    }
}

How It Works

  1. Existing key. apple is in the map, so its price changes to 45 and the old price 40 is returned.
  2. Missing key ignored. kiwi is not in the map, so replace returns null and adds nothing.
  3. Check it. containsKey("kiwi") confirms the failed replace left no trace.
  4. put inserts. put has no such restriction: it adds kiwi and the size grows to 3.

Example 2 — Book a Seat Only If It Is Still Free

replace(key, "free", "booked") succeeds once; repeating it fails because the seat is no longer free.

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

public class HashMapReplaceIfMatch {
    public static void main(String[] args) {
        Map<String, String> seats = new HashMap<>();
        seats.put("12A", "free");
        seats.put("12B", "booked");

        boolean first = seats.replace("12A", "free", "booked");
        boolean second = seats.replace("12A", "free", "booked");
        boolean other = seats.replace("12B", "free", "booked");

        System.out.println("first booking of 12A: " + first);
        System.out.println("second booking of 12A: " + second);
        System.out.println("booking 12B: " + other);
        System.out.println("12A is " + seats.get("12A"));
    }
}

How It Works

  1. Expected value matches. 12A is "free", so the first call changes it to "booked" and returns true.
  2. No double booking. The second identical call finds "booked" instead of "free" and changes nothing.
  3. Already taken. 12B was booked from the start, so it fails as well.
  4. Booleans, not values. The three-argument form reports success, which is exactly what booking logic needs to branch on.

Example 3 — Replacing and Setting null Values

Replace a null role, try a missing user, then set a role back to null with the three-argument form.

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

public class HashMapReplaceNull {
    public static void main(String[] args) {
        Map<String, String> roles = new HashMap<>();
        roles.put("ana", null);

        String r1 = roles.replace("ana", "admin");
        String r2 = roles.replace("bob", "admin");
        System.out.println("ana: returned " + r1 + ", now " + roles.get("ana"));
        System.out.println("bob: returned " + r2 + ", present? " + roles.containsKey("bob"));

        boolean cleared = roles.replace("ana", "admin", null);
        System.out.println("admin -> null: " + cleared + ", ana present? " + roles.containsKey("ana") + ", value " + roles.get("ana"));
    }
}

How It Works

  1. null-valued key is present. ana exists with a null role, so replace sets "admin" and returns the old null.
  2. Same return, different meaning. bob also returns null, but because he is missing; containsKey shows he was not added.
  3. null as the new value. HashMap allows null values, so replace("ana", "admin", null) succeeds and returns true.
  4. Key survives. Setting a value to null is not a removal: ana is still a key, now mapped to null.

Frequently Asked Questions

put() adds the key if it is missing; replace() only changes keys that already exist and otherwise does nothing.
The previous value, or null if the key was not present (or was mapped to null).
It replaces the value only if the key is currently mapped to oldValue (using equals) and returns true; otherwise it returns false.
Yes, in a HashMap. The key stays in the map with a null value.
Java 8 added both overloads.

Next: replaceAll()

Replace every value using a function.

replaceAll() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful