Interview Prep Zoneby CuriouserLabs

Question 5 of 5 · senior level

How do you choose the right collection? Compare Set/Map implementations and their ordering guarantees.

🎤 Say this first

Decide on three axes: ordering (none → Hash, insertion/access → LinkedHash, sorted → Tree), concurrency (single-thread → plain, concurrent → Concurrent/CopyOnWrite), and special keys (enums → EnumMap/EnumSet, priorities → PriorityQueue). Tree costs O(log n) but gives range queries and ordering; Hash* is O(1) but unordered. Choosing the tightest structure documents intent as much as it buys performance.

The full picture

NeedUseWhy
Fast lookup, no orderHashMap / HashSetO(1) expected
Predictable iteration orderLinkedHashMap / LinkedHashSethash speed + insertion order; LRU via access-order
Sorted keys, range queriesTreeMap / TreeSetred-black tree; headMap, ceilingKey, subSet
Enum keysEnumMap / EnumSetarray/bitset backed — fastest and smallest
Queue/stack both endsArrayDequering buffer; beats Stack & LinkedList
Priority schedulingPriorityQueuebinary heap; note: iteration is NOT sorted
Read-mostly listenersCopyOnWriteArrayListsnapshot iteration, zero read locking

Two habits mark a senior: (1) program to the interface — return List/Map/Collection from APIs, keep the implementation swappable; (2) immutability at boundaries — expose List.copyOf(...)/unmodifiable views so callers can't mutate your internals. Also know that TreeMap requires a total order consistent with equals, or Set semantics quietly break.

🔄 Likely follow-up questions

  • Design a data structure for top-K queries over a stream — which JDK pieces do you compose?
  • Why does PriorityQueue's iterator not return sorted order?
  • List.of() vs Collections.unmodifiableList vs Guava ImmutableList — semantic differences?