Java TreeMap put() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.TreeMap

Definition

In Java, put(key, value) stores value under key in a TreeMap. A new key is inserted at its sorted position, not at the end, so the map always prints and loops in key order. If the key is already there, only its value is replaced and the size stays the same.

The method returns the previous value for the key, or null when the key was new. "Already there" is decided by the map's ordering: a key counts as present when compareTo (or the map's Comparator) returns 0 for it, even if equals would say otherwise.

An instance method of java.util.TreeMap, part of TreeMap since Java 1.2. 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

Pass a key and a value; you get the old value back.

Java
TreeMap<String, String> phoneBook = new TreeMap<>();
String a = phoneBook.put("Mia", "555-0142");   // null (new key)
String b = phoneBook.put("Mia", "555-0199");   // "555-0142" (replaced)
CallWhat it does
map.put(k, v)Adds a new key in sorted position, or replaces the value of an existing one.
map.put(k, map.get(k) + 1)Updates from the old value (the key must exist, or unboxing null fails).
map.put(k, null)Allowed: TreeMap accepts null values.
map.put(null, v)Throws NullPointerException with natural ordering.

Values are autoboxed: scores.put("Ivy", 72) stores an Integer in a TreeMap<String, Integer>. Each call costs O(log n) because the tree is searched from the root.

Library declarations
Java
// java.util.TreeMap<K, V>
public V put(K key, V value)

// Declared in Map<K, V>; TreeMap implements it with a red-black tree

Parameters

ParameterDescription
key (K)The key. Must be comparable with the keys already in the map. Not null under natural ordering.
value (V)The value to store. May be null.

Return Value

Return ValueDescription
VThe value that was stored under an equal key before this call.
nullThe key was new, or it was previously mapped to null.

Compare with Similar Methods

Ways to store values in a TreeMap:

MethodHow it differs
putIfAbsent(k, v)Leaves an existing non-null value alone.
putAll(m)Copies every mapping of another map.
replace(k, v)Only changes existing keys; never inserts.
HashMap.put(k, v)Same contract, but no ordering and one null key allowed.

Java Examples

Example 1 — Build a Phone Book That Sorts Itself

Add three contacts in random order, change one number, and print the map.

Java
import java.util.TreeMap;

public class TreeMapPutPhoneBook {
    public static void main(String[] args) {
        TreeMap<String, String> phoneBook = new TreeMap<>();
        System.out.println(phoneBook.put("Mia", "555-0142"));
        phoneBook.put("Zane", "555-0110");
        phoneBook.put("Ava", "555-0187");
        String old = phoneBook.put("Mia", "555-0199");

        System.out.println("old number for Mia: " + old);
        System.out.println(phoneBook);
        System.out.println("entries: " + phoneBook.size());
    }
}

How It Works

  1. First insert prints null. The map is empty when Mia is added, so there is no previous number and put returns null.
  2. Second Mia call swaps the number. Mia already exists, so her value becomes 555-0199 and the old 555-0142 is handed back; the entry count stays at 3.
  3. Alphabetical without sorting. The contacts went in as Mia, Zane, Ava, yet the map prints Ava, Mia, Zane: each put placed its key at the right spot in the tree.

Example 2 — Count Votes With Case-Insensitive Names

With String.CASE_INSENSITIVE_ORDER, "anna" and "Anna" are the same key. Watch which spelling survives.

Java
import java.util.TreeMap;

public class TreeMapPutIgnoreCase {
    public static void main(String[] args) {
        TreeMap<String, Integer> votes = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        votes.put("Anna", 3);
        votes.put("bob", 2);
        Integer previous = votes.put("anna", 5);
        votes.put("BOB", 4);

        System.out.println("previous for anna: " + previous);
        System.out.println(votes);
        System.out.println("ANNA -> " + votes.get("ANNA"));
    }
}

How It Works

  1. The comparator defines "same key". CASE_INSENSITIVE_ORDER compares "anna" with "Anna" as 0, so put("anna", 5) finds the existing entry and returns its old value 3.
  2. The first spelling stays. put replaces only the value; the key object stored first is kept, which is why the map shows Anna and bob rather than anna and BOB.
  3. Lookups ignore case too. get("ANNA") goes through the same comparator and finds the entry holding 5.

Example 3 — A null Value Is Fine, a null Key Is Not

Store a null stock count, then try a null key on a naturally ordered map.

Java
import java.util.TreeMap;

public class TreeMapPutNullRules {
    public static void main(String[] args) {
        TreeMap<String, Integer> stock = new TreeMap<>();
        stock.put("pens", 40);
        stock.put("ink", null);
        System.out.println("null value stored: " + stock);

        try {
            stock.put(null, 5);
        } catch (NullPointerException e) {
            System.out.println("null key rejected: " + e.getClass().getSimpleName());
        }
        System.out.println("containsKey(\"ink\"): " + stock.containsKey("ink") + ", size " + stock.size());
    }
}

How It Works

  1. Unknown count, still a key. ink is stored with a null value and sorts before pens, because values never take part in the ordering.
  2. No way to compare null. To place a null key, the map would have to call compareTo on it, so natural ordering throws NullPointerException and nothing is added.
  3. Map left intact. After the failed call ink is still present and the size is 2, proving the exception did not damage the tree.

Frequently Asked Questions

The previous value stored under an equal key, or null if the key was new (or was mapped to null).
At its sorted position, decided by compareTo or the map's Comparator. Printing or looping over the map always follows key order, never insertion order.
Null values are allowed. A null key throws NullPointerException with natural ordering; only a Comparator that handles null explicitly can accept it.
When the comparator says two keys are equal (compare returns 0), put only replaces the value. The key object stored first stays in the map.
O(log n): the red-black tree is searched from the root and rebalanced after an insert. HashMap.put is usually faster but does not keep keys sorted.

Next: putAll()

Copy every mapping from another map into this one.

putAll() 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.

13 people found this page helpful