ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume II
  5. Tree-Based Collections
Book 1 · Volume II — Generics, Collections & Type System · Topic 5.3

Tree-Based Collections

TreeMap, TreeSet, ordering and Comparator

10 min readStage 1 · Foundations14 interview questions
Prerequisites
4.3 Set Implementations · 4.4 Map Implementations
Covers
TreeMap · TreeSet · Ordering · Comparator
Related
6.4 Algorithms (sorting) · 5.4 Equality & Hashing · B2V4 ConcurrentSkipListMap
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

TreeMap stores its entries in a red-black tree, a self-balancing binary search tree ordered by key; TreeSet is a TreeMap whose values are ignored. Every operation — get, put, remove, containsKey — is O(log n), iteration visits keys in sorted order, and navigation methods find neighbours and ranges efficiently.

A balanced red-black tree of keys
Figure 1 — A balanced red-black tree of keys

2Why It Exists

Hash tables answer "is this key present?" in constant time, but they cannot answer "what is the nearest key below 13:45?", "which events fall between 09:00 and 10:00?" or "who is first?" without scanning everything. Those questions need keys kept in order. A sorted array answers them with binary search, but every insert must shift the tail; a plain binary search tree inserts cheaply but degenerates into a list when keys arrive in sorted order, which ids and timestamps usually do (Figure 2).

Why TreeMap balances: the same keys in two trees
Figure 2 — Why TreeMap balances: the same keys in two trees

A self-balancing tree keeps both operations at O(log n) for any insertion order. Java chose the red-black tree because it needs at most two rotations per insert and three per delete, so changes stay cheap, at the price of a slightly taller tree than stricter schemes such as AVL trees.

3Core Concepts

TreeMap

Each entry is a node with key, value, left, right and parent references and a colour bit. Searching compares the target with each node's key and goes left or right. Insertions and deletions are followed by rotations and recolouring that keep the tree balanced: no path from the root to a leaf is more than twice as long as any other, so the height is at most about 2·log₂(n). As a NavigableMap, TreeMap supports floorKey, ceilingKey, lowerKey, higherKey, firstEntry, pollFirstEntry, and range views headMap, tailMap, subMap, descendingMap.

TreeSet

A NavigableSet implemented by a TreeMap with a dummy value per key. It inherits the same ordering, O(log n) costs and navigation methods: floor, ceiling, headSet, tailSet, subSet, descendingSet, pollFirst.

Navigation operations find neighbours and ranges
Figure 3 — Navigation operations find neighbours and ranges

Ordering

Order comes either from the keys' natural ordering — they implement Comparable — or from a Comparator supplied at construction. TreeMap uses only this ordering, never equals or hashCode: two keys are the same key if compare returns 0. The ordering must therefore be a consistent total order (antisymmetric, transitive), and ideally consistent with equals, otherwise the map behaves correctly as a sorted map but violates the general Map contract.

Natural ordering versus a supplied comparator
Figure 4 — Natural ordering versus a supplied comparator

Comparator

Comparator<T> is a functional interface returning a negative number, zero or a positive number. Since Java 8 comparators are built declaratively: Comparator.comparing(Order::customer).thenComparing(Order::total, Comparator.reverseOrder()), Comparator.nullsFirst(...), reversed(). Comparators must not change their result for keys already in the tree, and must not use subtraction for numeric comparison (overflow — B1V1 3.5).

4How It Works Internally

Because TreeMap does not hash, it has no resizing, no load factor and no bucket array: memory grows exactly with the number of entries, about 40 bytes per node plus keys and values. Every comparison is a method call on the key or comparator, so expensive compareTo implementations (for example comparing long strings) directly affect performance. Range views such as subMap are backed by the same tree and reflect later changes.

5APIs / Features / Syntax

NavigableMap and NavigableSet define the navigation API; TreeMap, TreeSet and their concurrent counterparts ConcurrentSkipListMap and ConcurrentSkipListSet implement it. The methods differ mainly in whether the bound is included:

Method (map / set)ReturnsBound
floorKey(k) / floor(e)Greatest key <= kInclusive
lowerKey(k) / lower(e)Greatest key < kExclusive
ceilingKey(k) / ceiling(e)Least key >= kInclusive
higherKey(k) / higher(e)Least key > kExclusive
headMap(k) / headSet(e)View of keys below kExclusive; overload with a boolean
tailMap(k) / tailSet(e)View of keys from kInclusive; overload with a boolean
subMap(a, b) / subSet(a, b)View of keys in [a, b)Overload with two booleans
firstEntry, pollFirstEntry, lastEntrySmallest or largest; poll removes it-
descendingMap() / descendingSet()Reverse-order view-

All the range methods return views backed by the tree, so later changes show through them, and inserting a key outside a view's range throws IllegalArgumentException. The *Key and floor style methods return null when no key qualifies, which callers must handle; the *Entry variants return immutable snapshots of the entry. Figure 5 shows how floorKey finds its answer on a single path from the root.

floorKey(13): one path from the root, remembering the best candidate
Figure 5 — floorKey(13): one path from the root, remembering the best candidate

6Practical Examples

Example 1 — Ordered collections in practice

Problem. Three typical ordered questions: rank players by score, find the configuration that applies to a version, and select the events of the last hour.

JAVAOrdered collections in practice
// Leaderboard: highest score first, then earliest time
record Score(String player, int points, Instant at) {}
NavigableSet<Score> board = new TreeSet<>(
    Comparator.comparingInt(Score::points).reversed()
              .thenComparing(Score::at)
              // tie-breaker keeps distinct players
              .thenComparing(Score::player));
board.add(new Score("asha", 90, t1));
List<Score> top10 = board.stream().limit(10).toList();

// Version ranges: which config applies to version 3.7?
NavigableMap<Version, Config> configs = new TreeMap<>();
Config applicable = configs.floorEntry(Version.of("3.7")).getValue();

// Time-window queries
NavigableMap<Instant, Event> events = new TreeMap<>();
Collection<Event> lastHour = events.tailMap(Instant.now().minus(1, ChronoUnit.HOURS), true).values();

Example 2 — Mini program: meeting-room bookings in a TreeMap

Problem. A booking service must reject a booking that overlaps an existing one, accept one that starts exactly when another ends, and list the free slots of the day. Bookings are kept in a TreeMap keyed by start time.

JAVARoomBooking.java
import java.time.LocalTime;
import java.util.*;
 
public class RoomBooking {
    record Booking(LocalTime start, LocalTime end, String who) { }
 
    private final NavigableMap<LocalTime, Booking> byStart = new TreeMap<>();
 
    boolean book(String who, String from, String to) {
        LocalTime s = LocalTime.parse(from), e = LocalTime.parse(to);
        var before = byStart.floorEntry(s);              // latest start <= s
        var after = byStart.ceilingEntry(s);             // earliest start >= s
        boolean clash = (before != null && before.getValue().end().isAfter(s))
                     || (after != null && after.getKey().isBefore(e));
        if (!clash) byStart.put(s, new Booking(s, e, who));
        System.out.printf("%-5s %s-%s %s%n", who, from, to,
                          clash ? "REJECTED" : "ok");
        return !clash;
    }
 
    List<String> freeSlots(LocalTime open, LocalTime close) {
        List<String> free = new ArrayList<>();
        LocalTime t = open;
        for (Booking b : byStart.subMap(open, true, close, false).values()) {
            if (t.isBefore(b.start())) free.add(t + "-" + b.start());
            t = b.end();
        }
        if (t.isBefore(close)) free.add(t + "-" + close);
        return free;
    }
 
    public static void main(String[] args) {
        RoomBooking room = new RoomBooking();
        room.book("asha", "09:00", "10:00");
        room.book("ravi", "11:30", "12:30");
        room.book("meera", "09:30", "10:30");            // overlaps asha
        room.book("john", "10:00", "11:30");             // fits exactly between
        room.book("li", "12:00", "13:00");               // overlaps ravi
        room.book("li", "14:00", "15:00");
        System.out.println("free  "
                + room.freeSlots(LocalTime.of(8, 0), LocalTime.of(17, 0)));
        System.out.println("first " + room.byStart.firstEntry().getValue().who()
                + ", last " + room.byStart.lastEntry().getValue().who());
        System.out.println("after noon "
                + room.byStart.tailMap(LocalTime.NOON).keySet());
    }
}
OUTPUT
asha  09:00-10:00 ok
ravi  11:30-12:30 ok
meera 09:30-10:30 REJECTED
john  10:00-11:30 ok
li    12:00-13:00 REJECTED
li    14:00-15:00 ok
free  [08:00-09:00, 12:30-14:00, 15:00-17:00]
first asha, last li
after noon [14:00]

Why it behaves this way. Only two neighbours can overlap a new booking: the latest booking that starts at or before it (floorEntry), which clashes if it ends after the new start, and the earliest that starts at or after it (ceilingEntry), which clashes if it starts before the new end. Both are O(log n), so the check does not scan the day. Meera's 09:30 start falls inside Asha's booking; John's 10:00-11:30 touches both neighbours but overlaps neither, because the times are half open. The free slots come from walking the sorted subMap view once.

Example 3 — A leaderboard that loses players

Problem. A leaderboard stores scores in a TreeSet sorted by points, highest first. After a busy day, players with equal scores are missing.

JAVALeaderboard.java
import java.util.*;
 
public class Leaderboard {
    record Score(String player, int points, long at) { }
 
    public static void main(String[] args) {
        List<Score> scores = List.of(new Score("asha", 90, 3),
                new Score("ravi", 75, 1), new Score("meera", 90, 2),
                new Score("john", 75, 4), new Score("li", 60, 5));
 
        Comparator<Score> byPoints =
                Comparator.comparingInt(Score::points).reversed();
        NavigableSet<Score> lossy = new TreeSet<>(byPoints);
        lossy.addAll(scores);
        System.out.println("points only : " + names(lossy));
 
        Comparator<Score> total = byPoints.thenComparingLong(Score::at)
                                          .thenComparing(Score::player);
        NavigableSet<Score> board = new TreeSet<>(total);
        board.addAll(scores);
        System.out.println("tie-breakers: " + names(board));
        System.out.println("top 2       : "
                + names(board.stream().limit(2).toList()));
        System.out.println("75 or more  : " + names(board.headSet(
                new Score("", 75, Long.MAX_VALUE), true)));
    }
 
    static List<String> names(Collection<Score> s) {
        return s.stream().map(x -> x.player() + ":" + x.points()).toList();
    }
}
OUTPUT
points only : [asha:90, ravi:75, li:60]
tie-breakers: [meera:90, asha:90, ravi:75, john:75, li:60]
top 2       : [meera:90, asha:90]
75 or more  : [meera:90, asha:90, ravi:75, john:75]

Why it behaves this way. With the points-only comparator, meera and asha compare as 0, so the set treats meera as a duplicate of asha and addAll drops her, as it drops john. Adding the time and then the player name as tie-breakers makes compare return 0 only for identical scores, so all five survive, and earlier scores rank first within equal points. The last line uses headSet with a probe score that sorts after every real 75: a range query on the ranking, not a filter.

Example 4 — Counting the comparisons behind O(log n)

Problem. "O(log n)" is abstract. Wrap the comparator in a counter, fill a TreeMap with sorted keys, the worst order for an unbalanced tree, and count the comparisons per put and per get.

JAVAComparisonCount.java
import java.util.*;
 
public class ComparisonCount {
    static long compares;
 
    public static void main(String[] args) {
        Comparator<Integer> counting = (a, b) -> {
            compares++;
            return Integer.compare(a, b);
        };
        for (int n : new int[] {1_000, 1_000_000}) {
            TreeMap<Integer, Integer> map = new TreeMap<>(counting);
            for (int i = 0; i < n; i++) map.put(i, i);   // sorted input
            long totalPut = compares;
            compares = 0;
            int lookups = 0;
            for (int k = 0; k < n; k += n / 100) {
                map.get(k);
                lookups++;
            }
            String f = "n=%,9d  log2(n)=%4.1f  per put=%4.1f  per get=%4.1f%n";
            System.out.printf(f,
                    n, Math.log(n) / Math.log(2), (double) totalPut / n,
                    (double) compares / lookups);
            compares = 0;
        }
    }
}
OUTPUT
n=    1,000  log2(n)=10.0  per put=14.5  per get=10.4
n=1,000,000  log2(n)=19.9  per put=34.4  per get=20.3

Why it behaves this way. A get costs about log2(n) comparisons, 20 for a million keys, because the red-black tree stays balanced even for sorted input. Each put of a new largest key walks the rightmost path, which in a red-black tree built from sorted keys is the longest one, close to the 2 log2(n) bound, so puts cost more than an average lookup. A plain binary search tree would have needed n/2 comparisons per lookup, 500,000 instead of 20.

7Common Problems & Mistakes

MistakeConsequenceBetter approach
Comparators that return 0 for distinct elements (e.g. comparing only by points)TreeSet silently drops "duplicates"; TreeMap overwrites their values (Example 3)Add tie-breakers, ending with a unique field such as an id
Keys that are not Comparable, and no comparatorClassCastException on the first put, even into an empty mapImplement Comparable or pass a Comparator
Mutating a key's sort fields after insertionThe key is now in the wrong position: get, remove and range views miss itImmutable keys; remove, change and re-insert
Subtraction-based comparators (a.x - b.x)Overflow for large or negative values gives a wrong order and breaks the tree (B1V1 3.5)Integer.compare, Comparator.comparingInt
TreeMap when only point lookups are neededAbout log2(n) comparisons and pointer chasing per lookup, several times slower than HashMapHashMap; sort only when ordered output is needed
Ignoring the null result of floorKey, ceilingEntry and friendsNullPointerException when the probe is below the first or above the last keyCheck for null, or seed the map with a sentinel such as a 00:00 entry

8Performance & Production Considerations

TreeMap is typically several times slower than HashMap for point lookups on large maps, because each lookup performs log₂(n) comparisons with pointer chasing — about 20 for a million keys. It shines where order is required: range scans, top-k, nearest matches. For concurrent sorted maps, use ConcurrentSkipListMap (B2V4); for very large sorted datasets, a database index is usually the right place.

9Architecture & Design Considerations

Sorted in-memory structures are the small-scale version of database B-tree indexes: both trade slower point access for efficient ordered and range access. When a design needs range queries on in-memory data — rate tables, schedules, time-series windows, order books — a NavigableMap expresses it directly and clearly.

10Interview Questions & Answers

Q1L1 · BasicConcept

What data structure does TreeMap use?

A red-black tree, a self-balancing binary search tree ordered by the keys' natural ordering or a supplied comparator.

Q2L2 · IntermediateConcept

What is the time complexity of TreeMap operations?

O(log n) for get, put, remove and containsKey, and for navigation methods like floorKey and ceilingKey. Iteration in sorted order is O(n).

Q3L2 · IntermediateInternals

How does TreeSet decide that two elements are duplicates?

By comparison: if compareTo or the comparator returns 0, they are treated as the same element, regardless of equals.

Q4L3 · Senior EngineerTricky

What does "comparator consistent with equals" mean and why does it matter?

compare(a, b) == 0 exactly when a.equals(b). If not consistent, a TreeSet or TreeMap still works as a sorted collection but may treat unequal elements as duplicates, so its behaviour differs from other Set or Map implementations.

Q5L3 · Senior EngineerScenario

A TreeSet-based leaderboard sometimes loses players with equal scores. Why, and how do you fix it?

The comparator compares only scores, so players with equal scores compare as 0 and the later one is treated as a duplicate. Add tie-breakers — timestamp, then player ID — so the comparator is a total order over distinct players.

Q6L4 · Technical ArchitectTrade-off

When would you choose a TreeMap over a database query for ordered data?

When the dataset fits comfortably in memory, is owned by one service instance, and needs very low-latency ordered or range access — rate tables, schedules, in-memory order books. If data must be shared, durable, very large or updated by many writers, a database index or dedicated store is more appropriate.

Q7L1 · BasicConcept

What is the difference between floorKey and lowerKey?

floorKey(k) returns the greatest key less than or equal to k, so it returns k itself when k is present; lowerKey(k) returns the greatest key strictly less than k. ceilingKey and higherKey are the same pair upwards. All four return null when no key qualifies.

Q8L2 · IntermediateCode

What does this program print?

JAVATreeQuiz.java
import java.util.*;
 
public class TreeQuiz {
    public static void main(String[] args) {
        TreeMap<Integer, String> rates =
                new TreeMap<>(Map.of(0, "night", 7, "day", 22, "evening"));
        System.out.println(rates.floorKey(7) + " " + rates.lowerKey(7) + " "
                + rates.higherKey(22));
        System.out.println(rates.headMap(7) + " " + rates.tailMap(7));
        NavigableMap<Integer, String> view = rates.descendingMap();
        rates.put(12, "noon");
        System.out.println(view.firstKey() + " " + view.keySet());
    }
}

It prints 7 0 null, then {0=night} {7=day, 22=evening}, then 22 [22, 12, 7, 0]. floorKey(7) includes 7, lowerKey(7) excludes it, and nothing is higher than 22. The one-argument headMap excludes its bound and tailMap includes it. descendingMap is a view, so the key 12 added afterwards appears in it, in descending order.

Q9L3 · Senior EngineerInternals

What keeps a red-black tree balanced?

Each node is red or black, the root is black, a red node never has a red child, and every path from a node down to its leaves has the same number of black nodes. Together these rules make the longest path at most twice the shortest, so the height is at most 2 log2(n + 1). An insert adds a red node and repairs any red-red violation by recolouring and at most two rotations; a delete needs at most three rotations.

Q10L3 · Senior EngineerTricky

Why can a TreeMap throw ClassCastException on the very first put?

Because put compares the key with itself when the map is empty, compare(key, key), precisely to check its type and reject null early. A key class that implements neither Comparable nor comes with a comparator therefore fails at once, instead of later when a second key arrives.

Q11L3 · Senior EngineerTrade-off

For a schedule of 100,000 events read far more often than changed, would you use a TreeMap or a sorted array with binary search?

A sorted array, or ArrayList with Collections.binarySearch, uses only the elements plus 4 bytes per reference and is cache-friendly, so lookups and range scans are faster; but each insert shifts the tail, O(n). TreeMap costs about 40 bytes per entry and pointer chasing, but inserts and removes in O(log n) and offers range views directly. If the schedule is rebuilt in bulk and then only queried, the sorted array; if events are added and cancelled continuously, TreeMap.

Q12L3 · Senior EngineerScenario

A rate lookup throws NullPointerException for transactions just after midnight. The code is rates.floorEntry(time).getValue(). What is wrong?

The earliest key in the map is later than the probe, for example the first rate starts at 00:30 or the table was loaded without its 00:00 entry, so floorEntry returns null. Validate the table when it is loaded, requiring an entry at the start of the domain, or handle the null explicitly with a clear error or a default rate. The same check applies to ceilingEntry at the upper end.

Q13L5 · Solution ArchitectDesign

How would you serve "price at time t" lookups for 5,000 instruments, each with a day of tick data, in a low-latency service?

Per instrument, a NavigableMap<Instant, Price> gives floorEntry(t) in O(log n); for heavy concurrent updates, ConcurrentSkipListMap offers the same API without a global lock. If the data is append-only and large, parallel primitive arrays of timestamps and prices with binary search use a fraction of the memory. Partition by instrument, bound the retained window, and keep historical queries in a time-series database rather than on the heap.

Q14L5 · Solution ArchitectTrade-off

When would you replace an in-memory TreeMap with a database index for ordered queries?

When the data no longer fits comfortably in one heap, must be shared by several instances, must survive restarts, or is written by many writers. A B-tree index provides the same ordered and range access with durability and concurrency, at the cost of a network round trip and query latency. The TreeMap remains the right tool for small, owned, latency-critical data, and often as a cache in front of the index.

Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • TreeMap/TreeSet = red-black tree; O(log n); sorted iteration; rich navigation.
  • Order from Comparable or a Comparator; compare == 0 means same key.
  • Make comparators total orders with tie-breakers; never subtract.
  • Use tree collections when order or ranges matter; HashMap otherwise.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.