SteelReed

Search

Search posts, questions…

2. Data Structures & Algorithms

Java Collections: TreeSet, TreeMap, Comparator and iterators

Why a leaderboard built on a TreeSet loses players and a remove-while-iterating loop throws ConcurrentModificationException; how to think about ordered data, comparators consistent with equals, NavigableMap for nearest and range queries; how to review collection code an AI wrote.

17 Nov 20267 min readMid

–

1. The problem

A leaderboard of 1,000 players lives in a TreeSet sorted by descending score. The top page shows only 880 players: 120 with tied scores have vanished. No exception, and the test with 5 distinct scores stays green.

2. Key idea

A search tree can only go left, go right, or stop. compare returning 0 means "already here": add returns false, put overwrites the value. A HashMap is a numbered locker, opening the right box instantly; a TreeMap is a shelf sorted alphabetically, a bit slower but able to answer "the nearest book before M".

Bug Symptom Root cause
Comparator without a tie-breaker size() smaller than the number added compare == 0 for two different elements
Mutating a field used as the key contains returns false for a just-added element the element sits in the wrong place in the tree
Modifying a collection while iterating CME, or sometimes no exception but skipped elements structural changes outside the iterator

2.1 Which structure?

Structure Use when Don't use when
HashMap, HashSet lookups by key (default), O(1) you need order or range queries
LinkedHashMap keeping insertion order, LRU caches you need key order
TreeMap, TreeSet nearest, ranges, always-sorted iteration, O(log n) you sort only once when printing
ConcurrentSkipListMap several threads and you need order single-threaded
CopyOnWriteArrayList very many reads, very rare writes (listeners) frequent writes: each one copies O(n)

2.2 Three rules

  • A comparator always ends with a unique key (id), so compare == 0 only when equals.
  • Never mutate the comparison fields of an element in a tree or used as a key; use immutable records.
  • Removing while iterating: removeIf or iterator.remove(), never list.remove in a for-each. Removing the second-to-last element in a for-each throws no CME but skips the last element: don't rely on the absence of an exception.

3. In Java

JAVA
// A final tie-breaker: nobody with a tied score gets swallowed
Comparator<Player> ranking = Comparator.comparingInt(Player::score).reversed()
        .thenComparingLong(Player::id);
NavigableSet<Player> board = new TreeSet<>(ranking);   // 1,000 in, 1,000 out
 
// Membership tiers: each key is the tier's starting threshold
NavigableMap<BigDecimal, String> tiers = new TreeMap<>(Map.of(
        BigDecimal.ZERO, "STANDARD",
        new BigDecimal("5000000"), "SILVER",
        new BigDecimal("20000000"), "GOLD"));
tiers.floorEntry(new BigDecimal("7500000")).getValue();   // "SILVER"
 
// Removing while iterating
sessions.removeIf(s -> s.expiresAt().isBefore(now));

Since Java 21, TreeMap is a SequencedMap: firstEntry(), lastEntry(), reversed() share names with LinkedHashMap. Other languages: C# has SortedSet<T> with IComparer and the same trap; Go and Node.js have no sorted tree in the standard library.

Comparable, Comparator and null keys

Comparable is the natural order inside the class (one of them: String alphabetically, LocalDate chronologically). A Comparator is an external order; you can have as many as you like, even for library classes.

null keys: HashMap allows one; TreeMap with natural ordering throws NullPointerException (it must call compareTo) unless you use Comparator.nullsFirst(...); ConcurrentHashMap forbids null keys and values.

Fail-fast relies on modCount: the iterator remembers the value at creation and rechecks on each next(). The Javadoc says to use it only to detect bugs, never to guarantee correctness.

4. Working with AI

Give the AI: Comparator chains from a spec, test data with tied scores, duplicate names and nulls; turning for-each loops with remove into removeIf.

Check in AI-written code:

  • Comparators for TreeSet/TreeMap end with a unique key.
  • No comparator built on subtraction (a.score - b.score).
  • Tests include elements tied on every key except id, and assert size() equals the number added.
  • No list.remove inside a for-each.
  • Collections shared in singleton beans are concurrent structures.

5. Exercises

Exercise 1: An AI-written leaderboard

The AI says "tested, sorted correctly by descending score", with 5 players scoring 100, 90, 80, 70, 60.

JAVA
NavigableSet<Player> board =
        new TreeSet<>(Comparator.comparingInt(Player::score).reversed());
void submit(Player p) { board.add(p); }

Find the bug, name a test that proves it, fix it.

Solution to Exercise 1

The comparator compares only scores: two players with the same score give compare == 0, and the TreeSet keeps whoever came first; add returns false but submit ignores it.

Test: 1,000 players with scores from new Random(42).nextInt(5000), assert board.size() == 1000. On JDK 21: bad=880 good=1000.

Fix: .thenComparingLong(Player::id). Another bug: when a player's score changes, remove the old entry and add the new one. With several instances, use a Redis sorted set (ZADD, ZREVRANGE).

Exercise 2: A CME at 2 a.m.

A cleanup job sometimes fails with ConcurrentModificationException at ArrayList$Itr.checkForComodification; rerunning it by hand works. The job iterates activeSessions, an ArrayList in a singleton bean, while login requests keep adding to it. Diagnose and fix.

Solution to Exercise 2

One thread iterates while another modifies the structure; fail-fast only catches some of these. The runs that don't throw are worse: ArrayList isn't thread-safe, so elements can be lost or skipped.

Fix: sessions keyed by id in a ConcurrentHashMap, with removeIf on values() (a weakly consistent iterator that never throws CME). With several instances, sessions belong in Redis or the database, with a TTL.

Summary

  • TreeSet/TreeMap define duplicates by compare, not equals.
  • Comparators always end with a unique key.
  • TreeMap for nearest or range queries; otherwise HashMap.
  • Remove while iterating with removeIf or iterator.remove().
  • Fail-fast is best effort; for several threads use concurrent structures.

Read more: List, Set, Map.

Practice interview questions on this topic

All Collections & DSA questions →

Loading comments…