Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Collections, From the Inside

    TreeMap and TreeSet: Always Sorted

    TreeMap<K, V> keeps its keys sorted at all times. TreeSet<E> is a sorted set (it's a TreeMap inside, like HashSet/HashMap).

    Chapter 6 of 114 min read

    The Plain Picture#

    A dictionary (the book). Words are always in alphabetical order, so you can open it near the right page, and answer questions like "what's the last word before mitochondria?" or "list every word from cat to cow".

    The Real Names#

    • TreeMap<K, V> keeps its keys sorted at all times. TreeSet<E> is a sorted set (it's a TreeMap inside, like HashSet/HashMap).

    • Inside is a red-black tree: a kind of binary search tree that rebalances itself on every insert/delete so its height stays about log n (the mechanics are in Binary Trees and Binary Search Trees (coming soon)). So get, put, remove are O(log n) — slower than a HashMap's O(1), but you get order.

    • Keys must be comparable: they implement Comparable, or you pass a Comparator (Ch 7). null keys aren't allowed.

    Under the Hood — the navigation methods (the reason to use a TreeMap)#

    A leaderboard, score → student:

    Java
    TreeMap<Integer, String> board = new TreeMap<>(Map.of(200, "Priya", 150, "Rahul", 110, "Vikram", 180, "Aisha"));
    
    board.firstKey()          // 110              smallest key
    board.lastEntry()         // 200=Priya        largest entry
    board.floorKey(170)       // 150              largest key  ≤ 170
    board.ceilingKey(170)     // 180              smallest key ≥ 170
    board.higherKey(200)      // null             smallest key > 200 (none)
    board.headMap(180)        // {110=Vikram, 150=Rahul}     all keys < 180
    board.descendingMap()     // {200=Priya, 180=Aisha, 150=Rahul, 110=Vikram}

    Also lowerKey (< k), tailMap(k) (≥ k), subMap(a, b) (a ≤ key < b), pollFirstEntry() (remove and return the smallest). TreeSet has first, last, floor, ceiling, higher, lower, pollFirst, pollLast:

    Java
    TreeSet<Integer> ts = new TreeSet<>(List.of(5, 1, 9, 3));
    
    System.out.println(
        ts + " " + ts.first() + " " + ts.floor(4) + " " + ts.pollFirst() + " " + ts
    );
    // [1, 3, 5, 9] 1 3 1 [3, 5, 9]

    Each navigation method is O(log n). A HashMap can't answer "the nearest key below 170" at all without scanning everything.

    DSA uses: "is there a booking that overlaps this new time slot?" (check floorKey and ceilingKey of the start time), sliding-window problems that need the current minimum/maximum with removals, "count of smaller numbers", calendar and interval problems (Intervals (coming soon)).

    Gotcha: a TreeMap decides "same key" using compareTo/the comparator, not equals. If your comparator says two different students are "equal" (e.g. comparing only by score), the second one replaces the first. That's why the leaderboard above maps score → name, and why comparators for tree keys should break ties (Ch 7).

    Check yourself

    4 questions
    1

    When would you choose TreeMap over HashMap?

    Show answer

    When you need keys in sorted order or nearest/range queries (floor, ceiling, head/tail maps).

    2

    What do floorKey(k) and ceilingKey(k) return?

    Show answer

    The largest key ≤ k; the smallest key ≥ k (or null if none).

    3

    What's the cost of put and floorKey in a TreeMap?

    Show answer

    O(log n) each.

    4

    Why can two different keys "collide" in a TreeMap?

    Show answer

    TreeMap treats keys as the same when the comparator returns 0, even if equals says they differ.