Java TreeMap 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 TreeMap, and returns the old value. If the key is missing, nothing happens and it returns null. It never inserts.

The three-argument form replace(key, oldValue, newValue) changes the value only when the current value equals oldValue, and returns true or false. Both forms find the key with the map's ordering, so a comparator-equal key is enough.

An instance method of java.util.TreeMap, added in Java 8 as part of the Map interface. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.

Syntax

Two overloads: plain replace and conditional replace.

Java
TreeMap<String, Integer> menu = new TreeMap<>();
menu.put("latte", 4);
Integer old = menu.replace("latte", 6);          // 4
boolean ok = menu.replace("latte", 6, 7);        // true: was 6, now 7
CallWhat it does
map.replace(k, v)Replaces the value if k exists; returns the old value or null.
map.replace(k, oldV, newV)Replaces only when the current value equals oldV.
map.replace(missing, v)Does nothing; returns null.

replace changes values only, never the structure of the tree, so it does not disturb an iteration that is running over the map.

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

// Default methods of Map<K, V> since Java 8; TreeMap overrides both

Parameters

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

Return Value

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

Compare with Similar Methods

Updating values:

MethodHow it differs
put(k, v)Updates or inserts.
replaceAll(f)Rewrites every value with a function.
computeIfPresent(k, f)Computes the new value from the old one; null removes.
HashMap.replaceSame two overloads on an unordered map.

Java Examples

Example 1 — Update Coffee Prices Without Adding Items

Raise the latte price and try to "update" tea, which is not on the menu.

Java
import java.util.TreeMap;

public class TreeMapReplaceMenu {
    public static void main(String[] args) {
        TreeMap<String, Integer> menu = new TreeMap<>();
        menu.put("latte", 4);
        menu.put("mocha", 5);

        Integer oldLatte = menu.replace("latte", 6);
        Integer oldTea = menu.replace("tea", 3);

        System.out.println("latte was " + oldLatte);
        System.out.println("tea was " + oldTea);
        System.out.println(menu);
    }
}

How It Works

  1. An existing item changes. latte is on the menu, so its price becomes 6 and the old price 4 is returned.
  2. A missing item is ignored. tea is not a key, so replace returns null and, unlike put, does not add it.
  3. Menu size unchanged. The printed map still has exactly latte and mocha, in alphabetical order.

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

The three-argument form acts as a check-and-set: it books a seat only when its status is still "free".

Java
import java.util.TreeMap;

public class TreeMapReplaceSeats {
    public static void main(String[] args) {
        TreeMap<Integer, String> seats = new TreeMap<>();
        seats.put(1, "free");
        seats.put(2, "booked");
        seats.put(3, "free");

        boolean a = seats.replace(2, "free", "booked");
        boolean b = seats.replace(3, "free", "booked");
        boolean c = seats.replace(9, "free", "booked");

        System.out.println("seat 2 booked now? " + a);
        System.out.println("seat 3 booked now? " + b);
        System.out.println("seat 9 booked now? " + c);
        System.out.println(seats);
    }
}

How It Works

  1. Seat 2 is taken. Its value is "booked", not "free", so the condition fails and the method returns false.
  2. Seat 3 matches. The current value equals "free", so it becomes "booked" and the call returns true.
  3. Seat 9 does not exist. There is no key 9 to compare, so the result is false and no seat is created.

Example 3 — Replace Using a Differently Spelled Key

In a case-insensitive map, "APPLE" finds the entry stored as "Apple".

Java
import java.util.TreeMap;

public class TreeMapReplaceIgnoreCase {
    public static void main(String[] args) {
        TreeMap<String, Integer> stock = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        stock.put("Apple", 10);
        stock.put("banana", 6);

        Integer old = stock.replace("APPLE", 12);
        boolean swapped = stock.replace("BANANA", 6, 9);

        System.out.println("old APPLE value: " + old + ", banana swapped: " + swapped);
        System.out.println(stock);
    }
}

How It Works

  1. Found through the comparator. CASE_INSENSITIVE_ORDER treats "APPLE" and "Apple" as equal, so the stock of 10 is replaced by 12.
  2. Conditional form works the same way. "BANANA" locates banana, its value 6 equals the expected 6, and it becomes 9.
  3. Stored spellings unchanged. The map still prints Apple and banana: replacing a value never swaps the key object.

Frequently Asked Questions

No. If the key is not present, replace(key, value) returns null and replace(key, old, new) returns false; the map is unchanged.
put inserts or updates. replace only updates keys that already exist.
With equals (null-safe). The value changes only if the current value equals oldValue.
No. Only the value changes; the key and its position in the tree stay the same.
Java 8 added both overloads as default methods of Map, and TreeMap overrides them for a single tree search.

Next: replaceAll()

Rewrite every value with a function of key and value.

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.

10 people found this page helpful