Skip to the page

Collections and generics · mid

Ordered maps, TreeMap and comparators

TreeMap and TreeSet use a comparator, not equals. LinkedHashMap keeps order and can build an LRU cache. Comparators must not overflow or drop items.

The notes

What you must know

  • TreeMap is a red-black tree with keys sorted by natural order or a Comparator. get, put and floor or ceiling lookups are O(log n).
  • Slabs: key a TreeMap by each slab's lower bound and call floorEntry(value).getValue(). floorEntry returns null below the smallest key. Use long paise, never double.
  • NavigableMap methods: floorKey, ceilingKey, higherKey, lowerKey, headMap, tailMap, subMap, firstEntry, lastEntry.
  • Tree collections compare with compareTo or the Comparator, not equals. If compare returns 0, the element counts as a duplicate and is dropped from a TreeSet.
  • a - b as a comparator can overflow int. Use Integer.compare or Comparator.comparingInt(...).thenComparing(...).
  • Comparable: one natural order inside the class. Comparator: any number of orders from outside. Keep compareTo consistent with equals.
  • LRU cache: extend LinkedHashMap with super(capacity, 0.75f, true) for access order and override removeEldestEntry. By hand: a HashMap plus a doubly linked list.
  • With access order, even get changes the list, so reads need a lock when threads share it. In production use Caffeine, or Redis when pods must share the cache. Publish a reloaded slab map through a volatile field or AtomicReference so readers see the old or the new map, never half of one.

The red pen

Common traps: mistake → fix

  • Mistake: TreeSet uses equals to find duplicates

    Fix: it uses the comparator; compare equal to 0 means same.

  • Mistake: a - b is a fine comparator

    Fix: it overflows for large values.

  • Mistake: LinkedHashMap is only for insertion order

    Fix: with access order it is the base of an LRU cache.

Easy to hard

Questions interviewers ask, easy to hard

  1. Which collection finds the delivery fee for a cart value from slabs?
  2. Why does a TreeSet of 1,000 orders show only 874?
  3. How do you write an LRU cache in Java?
  4. Comparable or Comparator?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview