TreeMap in Java

TreeMap stores key-value pairs in sorted key order using a red-black tree, providing O(log n) operations and powerful navigation methods.

TreeMap<K, V> is a NavigableMap implementation backed by a red-black tree. It keeps all entries sorted by key — either via the keys' natural ordering (Comparable) or a custom Comparator supplied at construction time. Every operation runs in guaranteed O(log n) time. TreeMap is the go-to choice when you need a map with sorted keys, range queries, or navigation operations like finding the closest key.

How TreeMap Works Internally

TreeMap maintains a self-balancing red-black tree where each node holds one key-value pair. The tree is kept sorted by key at all times. Insertions, deletions, and lookups traverse the tree top-down in O(log n) comparisons. Rebalancing (rotations and recolouring) after mutations is also O(log n).

Operation Time complexity
put O(log n)
get O(log n)
remove O(log n)
firstKey / lastKey O(log n)
floorKey / ceilingKey O(log n)
headMap / tailMap / subMap O(log n) to establish view
Iteration (in order) O(n)

Key characteristics:

  • Keys are always in sorted (ascending) order.
  • null keys are not permitted with natural ordering (throws NullPointerException).
  • null values are permitted.
  • Not thread-safe.
  • Implements NavigableMap, which extends SortedMap.

Examples

Sorted key iteration and navigation

import java.util.TreeMap;
import java.util.NavigableMap;

public class TreeMapBasics {
    public static void main(String[] args) {
        NavigableMap<String, Integer> population = new TreeMap<>();
        population.put("Berlin", 3_645_000);
        population.put("Paris", 2_161_000);
        population.put("London", 8_982_000);
        population.put("Madrid", 3_223_000);

        // Keys are always in natural (alphabetical) order
        population.forEach((city, pop) ->
            System.out.printf("%-10s %,d%n", city, pop));
        // Berlin     3,645,000
        // London     8,982,000
        // Madrid     3,223,000
        // Paris      2,161,000

        System.out.println(population.firstKey());       // Berlin
        System.out.println(population.lastKey());        // Paris
        System.out.println(population.floorKey("M"));    // London (greatest key ≤ "M")
        System.out.println(population.ceilingKey("M"));  // Madrid (smallest key ≥ "M")
    }
}

Range view and custom Comparator

import java.util.Comparator;
import java.util.TreeMap;
import java.util.SortedMap;

public class TreeMapRange {
    public static void main(String[] args) {
        // Store version strings sorted by natural order
        TreeMap<String, String> releases = new TreeMap<>();
        releases.put("1.0", "Initial release");
        releases.put("1.2", "Bug fixes");
        releases.put("2.0", "Major rewrite");
        releases.put("2.1", "Performance improvements");
        releases.put("3.0", "Next generation");

        // All releases from 1.2 (inclusive) to 2.1 (inclusive)
        SortedMap<String, String> range = releases.subMap("1.2", true, "2.1", true);
        range.forEach((v, desc) -> System.out.println(v + ": " + desc));
        // 1.2: Bug fixes
        // 2.0: Major rewrite
        // 2.1: Performance improvements

        // Reverse iteration
        releases.descendingMap().forEach((v, desc) ->
            System.out.println(v + " -> " + desc));
    }
}

Common Mistakes

  1. Inserting null keys with natural ordering. TreeMap calls compareTo (or the Comparator) during every insertion. Inserting a null key throws NullPointerException because null.compareTo(...) fails. HashMap accepts a single null key; TreeMap does not.

  2. Inconsistent Comparator or compareTo. If compareTo returns 0 for two keys that equals considers different (or vice versa), TreeMap will treat them as duplicates and overwrite entries unexpectedly. Ensure the ordering is consistent with equals.

  3. Subtraction-based comparators. (a, b) -> a - b overflows for values near Integer.MAX_VALUE. Use Integer.compare(a, b) or Comparator.comparingInt(...).

  4. Assuming subMap / headMap / tailMap views are copies. Range views are live, backed views of the same tree. Inserting an out-of-range key into a view throws IllegalArgumentException; modifications in the view affect the original map.

  5. Using TreeMap when HashMap is sufficient. If sorted order is not needed, HashMap is faster (O(1) vs O(log n)). Only use TreeMap when key ordering, range queries, or navigation methods are required.

Best Practices

  • Declare variables as NavigableMap<K, V> or SortedMap<K, V> to expose the sorting API.
  • Provide an explicit Comparator rather than relying on natural ordering when the key type's compareTo may not match equals.
  • Use floorKey, ceilingKey, headMap, tailMap, and subMap for efficient range-based operations.
  • Use Comparator.comparing(...) chains instead of subtraction-based comparators to avoid overflow.
  • For concurrent access, wrap with Collections.synchronizedSortedMap or use a ConcurrentSkipListMap.

Interview Questions

1. What data structure does TreeMap use internally?

TreeMap uses a red-black tree — a self-balancing binary search tree. Each node stores one key-value entry, and the tree is kept sorted by key at all times. Balancing is done via rotations and recolouring after every insertion or deletion, ensuring O(log n) height and therefore O(log n) operations.

2. Why does TreeMap not support null keys?

Every insertion and lookup requires comparing the new key against existing keys using compareTo or the supplied Comparator. Calling compareTo on a null reference throws NullPointerException. HashMap handles null specially (bucket 0 and a null-check in the put path), but TreeMap has no such special case.

3. What is the difference between TreeMap and HashMap?

HashMap provides O(1) average operations with no ordering guarantee. TreeMap provides O(log n) guaranteed operations and keeps keys in sorted order. TreeMap supports rich navigation (floorKey, ceilingKey, range views); HashMap does not. Use HashMap for raw speed; use TreeMap when sorted keys or range queries are needed.

4. How do headMap, tailMap, and subMap work?

These methods return live NavigableMap views backed by the same tree. headMap(toKey) returns all entries with keys strictly less than toKey. tailMap(fromKey) returns all entries with keys greater than or equal to fromKey. subMap(fromKey, toKey) returns entries in the range [fromKey, toKey). All views enforce their bounds and reflect any changes to the original map.

5. How do you sort TreeMap entries by value instead of key?

TreeMap always sorts by key. To sort by value, stream the entrySet() and sort by value, or collect into a LinkedHashMap that preserves insertion order after sorting. You cannot make TreeMap itself sort by value.

6. What is ConcurrentSkipListMap and how does it relate to TreeMap?

ConcurrentSkipListMap is a thread-safe, concurrent NavigableMap that uses a skip list instead of a red-black tree. It provides the same sorted-key guarantee as TreeMap with O(log n) operations, but allows concurrent reads and writes without locking the entire structure. Use it when multiple threads need concurrent sorted-map access.

7. What happens if a Comparator is inconsistent with equals in TreeMap?

TreeMap uses the comparator (not equals) to determine key equality. If comparator.compare(a, b) == 0 but a.equals(b) is false, the map treats them as the same key and overwrites the value. If comparator.compare(a, b) != 0 but a.equals(b) is true, the map stores both as separate entries, violating the Map contract that says keys must be unique per equals.

Summary

  • TreeMap is backed by a red-black tree and keeps entries in sorted key order with O(log n) operations.
  • null keys are not permitted; null values are.
  • It implements NavigableMap, providing floorKey, ceilingKey, range views, and reverse iteration.
  • Comparators or compareTo implementations must be consistent with equals.
  • Use HashMap for speed; use TreeMap when sorted key access or range queries are required.

Continue Learning

Previous: LinkedHashMap | Next: Hashtable

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.