Java TreeMap

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

Definition and Usage

In Java, TreeMap (in java.util, since Java 1.2) stores key/value pairs sorted by key, like a dictionary or a phone book. put() stores a pair, get() reads a value, and remove() deletes it.

Inside is a red-black tree (a self-balancing binary search tree), so get, put, containsKey, and remove take O(log n) time. It implements NavigableMap (Java 6), SortedMap, Map, Cloneable, and Serializable. The TreeMap Methods index lists every guide.

Two rules to remember.

A TreeMap is not thread-safe: wrap it with Collections.synchronizedSortedMap or use ConcurrentSkipListMap. Its iterators are fail-fast: changing the keys while looping throws ConcurrentModificationException, so remove through the iterator or removeIf.

Java Syntax

Import the class, then create a map. Pass a Comparator to change the order:

Java
import java.util.Comparator;
import java.util.NavigableMap;
import java.util.TreeMap;

TreeMap<String, Integer> ages = new TreeMap<>();      // natural order
NavigableMap<Integer, String> desc = new TreeMap<>(Comparator.reverseOrder());
TreeMap<String, Integer> noCase = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

ages.put("Lina", 29);            // 29 is autoboxed to Integer
Integer b = ages.get("Omar");    // null (no such key)

Declare the variable as TreeMap or NavigableMap (not just Map) to reach navigation methods such as floorKey().

How Keys Are Ordered

Each key is placed by comparing it with the keys already in the tree: by its own compareTo (natural ordering) or by the map's Comparator. comparator() tells you which.

RuleWhat it means for you
Natural orderingInteger keys sort numerically; String keys by character code, so "Zoe" comes before "adam".
Comparator-based key equalityKeys are the same key when compare returns 0: with String.CASE_INSENSITIVE_ORDER, "Anna" and "anna" share one entry, and the first key object is kept.
Null rulesA null key throws NullPointerException with natural ordering; null values are fine.
Comparable keysKeys that are not Comparable (and no comparator) throw ClassCastException, even on the first put.

TreeMap vs HashMap, LinkedHashMap, and Others

All implement Map; they differ in order, speed, and null rules:

ClassOrderKeep in mind
TreeMapSorted by keyO(log n) operations; navigation and range views; no null key with natural ordering
HashMapNone guaranteedUsually the fastest map (constant time on average); one null key allowed
LinkedHashMapInsertion order (or access order)A HashMap with a linked list through the entries; supports putFirst/putLast in Java 21

Java 21: TreeMap is a SequencedMap, but since the tree decides where keys go, putFirst() and putLast() always throw UnsupportedOperationException; reversed() returns descendingMap().

Java Examples

Example 1 — A Class Roster Sorted by Roll Number

Add four pupils in random order, read one, remove one, and loop over the rest; the keys stay sorted.

Java
import java.util.Map;
import java.util.TreeMap;

public class TreeMapBasics {
    public static void main(String[] args) {
        TreeMap<Integer, String> roster = new TreeMap<>();
        roster.put(17, "Nadia");
        roster.put(3, "Tomas");
        roster.put(42, "Wen");
        roster.put(8, "Priya");

        System.out.println(roster);
        System.out.println("roll 42: " + roster.get(42));
        roster.remove(3);
        System.out.println("first roll now: " + roster.firstKey() + ", last: " + roster.lastKey());

        for (Map.Entry<Integer, String> e : roster.entrySet()) {
            System.out.println(e.getKey() + ". " + e.getValue());
        }
    }
}

How It Works

  1. Numbers sort as numbers. The rolls went in as 17, 3, 42, 8, yet the map prints 3, 8, 17, 42, because Integer keys use numeric natural ordering.
  2. Ends move with the data. After roll 3 is removed, firstKey() is 8 while lastKey() stays 42.
  3. A loop in key order. entrySet() walks the remaining pupils from the smallest roll number to the largest, giving a ready-made class list.

Example 2 — Find the Last and the Next Train

Zero-padded times sort as text in time order, so navigation methods answer "before" and "after" directly.

Java
import java.util.TreeMap;

public class TreeMapNavigationTour {
    public static void main(String[] args) {
        TreeMap<String, String> departures = new TreeMap<>();
        departures.put("07:15", "Leeds");
        departures.put("08:40", "York");
        departures.put("09:05", "Hull");
        departures.put("10:30", "Derby");

        String now = "08:50";
        System.out.println("last train gone: " + departures.floorEntry(now));
        System.out.println("next train: " + departures.ceilingEntry(now));
        System.out.println("already left: " + departures.headMap(now).keySet());
        System.out.println("still to come: " + departures.tailMap(now).keySet());
    }
}

How It Works

  1. No exact match needed. 08:50 is not a key, yet floorEntry returns the closest earlier departure (08:40 York) and ceilingEntry the closest later one (09:05 Hull).
  2. Split at a point in time. headMap(now) holds the times before 08:50 and tailMap(now) those from 08:50 on, without copying anything.
  3. Why zero-padding matters. "07:15" sorts before "10:30" only because every hour has two digits; "7:15" would sort after "10:30" as text.

Example 3 — Reverse Order and Case-Insensitive Keys

A leaderboard sorted from high to low, and the same names counted with and without case sensitivity.

Java
import java.util.Comparator;
import java.util.TreeMap;

public class TreeMapOrderingRules {
    public static void main(String[] args) {
        TreeMap<Integer, String> leaderboard = new TreeMap<>(Comparator.reverseOrder());
        leaderboard.put(870, "Ola");
        leaderboard.put(1250, "Ken");
        leaderboard.put(990, "Bea");
        System.out.println("high to low: " + leaderboard);

        TreeMap<String, Integer> natural = new TreeMap<>();
        TreeMap<String, Integer> noCase = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        String[] names = {"bob", "Alice", "alice", "Carl"};
        for (String n : names) {
            natural.merge(n, 1, Integer::sum);
            noCase.merge(n, 1, Integer::sum);
        }
        System.out.println("natural: " + natural);
        System.out.println("ignore case: " + noCase);
    }
}

How It Works

  1. Reverse comparator, reverse map. Comparator.reverseOrder() flips the numeric order, so the top score 1250 is printed first.
  2. Capitals first by default. Natural String order compares character codes, and every uppercase letter comes before every lowercase one, giving Alice, Carl, alice, bob.
  3. One key for two spellings. With CASE_INSENSITIVE_ORDER, "alice" equals "Alice", so the counts merge into Alice=2 and the names sort A, b, C regardless of case.

Next: Java TreeMap Methods by Group

Descriptions of each: Java TreeMap Methods index.

Frequently Asked Questions

A java.util class that stores key/value pairs sorted by key in a red-black tree, so get, put, containsKey, and remove take O(log n) time. It implements NavigableMap, SortedMap, and Map.
By the keys' natural ordering (compareTo) or by a Comparator passed to the constructor. Two keys that compare as 0 are the same key, even if equals() says they differ.
Null values are fine. A null key throws NullPointerException with natural ordering; only a Comparator that handles null can accept one.
No. Wrap it with Collections.synchronizedSortedMap(...) and synchronize on the wrapper while iterating, or use ConcurrentSkipListMap.
When you need keys in sorted order or nearest-key and range questions such as "the largest key at most 84". Otherwise HashMap is usually faster.

Browse every TreeMap method

Open the methods index for categorized guides with examples and FAQs.

TreeMap Methods Index →

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.

9 people found this page helpful