Lesson · Collections Framework
Choosing the right collection
16 min readChoosing the Right Collection
Four questions pick every collection in the framework: what a slot holds, how you find an item, what order matters, and who else touches the data. Answer them in order and the type names itself.
The same task, two different lifetimes
Counting how often each word appears. The hand-rolled version scans one list for each word it meets; the framework version is one loop:
Map<String, Integer> counts = new HashMap<>(); for (String w : words) { counts.merge(w, 1, Integer::sum); // add 1, or add to what is there } System.out.println(counts.get("go")); // 3
Predict: what does the choice of HashMap buy here? A list of pairs would need a scan per word: O(n) per lookup, O(n squared) for the whole count. The map answers in constant expected time, and merge makes the increment a single expression.
The four questions
Collections are not memorised; they are derived. Ask in this order:
- What does one slot hold? A single value, or a key with a value? A key means Map, and the first branch is decided.
- How do you find an item? By position (
get(i)) means List; by membership (contains) means Set or Map; always taking from an end means Queue or Deque. - What order matters? None: hash-based, the fastest. Insertion order: the Linked variants. Sorted: the Tree variants, which compare instead of hash.
- Who else touches it? Shared between threads changes the final answer: ConcurrentHashMap, CopyOnWriteArrayList, PriorityBlockingQueue and the rest of java.util.concurrent.
The questions are filters, not a quiz. Each answer eliminates a branch of the hierarchy; after three or four, one type remains, and it is usually the obvious one.
Decision walker · four questions to one type
answer to narrow the branchWhat does one slot hold?
Two types that both fit? Take the simpler one. Thread safety changes the final type, never the branch.
The decision table
The complete mapping, including the watch-outs that bite in review:
| If you need | Reach for | Why | Watch out for |
|---|---|---|---|
| Lookup by key | HashMap | O(1) expected put and get | no iteration order promised |
| Lookup by key, in insertion order | LinkedHashMap | thread an order through the entries | more memory per entry |
| Lookup by key, sorted, with ranges | TreeMap | O(log n) plus floorKey, subMap | keys need an order; comparisons on every operation |
| Unique values | HashSet | fastest membership test | order unspecified |
| Unique, in first-seen order | LinkedHashSet | dedupe that keeps the order usable | more memory than HashSet |
| Unique, sorted | TreeSet | order plus range queries | comparator must be consistent with equals |
| Position access | ArrayList | O(1) get and set | inserts in the middle shift the tail |
| Queue or stack | ArrayDeque | O(1) at both ends | not thread safe |
| Always the smallest or most urgent next | PriorityQueue | O(log n) offer and poll | iteration is not sorted; peek only shows the top |
| Counting occurrences | HashMap plus merge | the standard idiom | boxed Integer counters |
| Least recently used cache | LinkedHashMap in access order | removeEldestEntry does the eviction | must subclass to enable it |
| Shared between threads | ConcurrentHashMap, CopyOnWriteArrayList, PriorityBlockingQueue | atomic compound operations, safe iteration | weaker snapshot semantics than a locked collection |
Four mispicks you will meet in the wild
These four patterns account for most production slowdowns and surprising test failures.
- LinkedList as the general-purpose list. Its
get(i)walks from an end, so index-heavy code silently degrades. ArrayList is the default; reach for LinkedList or ArrayDeque only when the ends are the hot spot. - ArrayList as a queue.
remove(0)shifts every remaining element. ArrayDeque exists precisely for this and is faster at both ends. - HashMap when order is silently depended on. Tests that pass because small maps happen to iterate in insertion order fail later with more entries. Need order: say so with LinkedHashMap.
- A HashSet of objects whose equals fields mutate. The object lands in the wrong bucket and lookups miss. Keys of hash-based collections must stay stable while stored.
Every mispick is a promise mismatch. The type promised something the code did not need (order, speed at the ends) or needed something the type did not promise.
The pipeline in the demo
The demo runs the whole chain from one word array: count, dedupe, rank, and schedule.
HashMapplusmergecounts the words.LinkedHashSetremoves duplicates and keeps first-seen order.PriorityQueuewith a composed comparator ranks by count, ties alphabetical: the same pattern as any top-k report.ArrayDequemodels work arriving at both ends:addFirstjumps the line,pollFirstandpollLasttake from either side.
The choosing playbook
Deciding a collection, in order:
- Answer the four questions before opening the API docs.
- Default to the simplest type that fits: HashMap, ArrayList, HashSet, ArrayDeque.
- Add order only when something observes it: Linked for insertion, Tree for sorted.
- Add thread safety only with a named need, and pick from java.util.concurrent rather than wrapping.
- Re-check any collection that outlives the method it was created in: promises that fit one use often fail the next.
Types are promises, and choices are promises you make. Ask what the code needs, pick the narrowest promise, and the collection chooses itself.
Four questions, one answer
What does a slot hold; how is it found; what order matters; who shares it. Each answer eliminates a branch of the collection hierarchy, and when two types both fit, the simpler one wins. The defaults to reach for first: HashMap, ArrayList, HashSet, ArrayDeque, with Linked and Tree variants added only when order is observed and java.util.concurrent when threads are.
Interview angles
Walk your standard collection decision process.+
Key and value, or single values? Then position, membership or ends. Then whether any order is observed. Then whether threads share it. The type falls out of the four answers.
The order of the questions matters: slot shape eliminates the most types first, and thread safety is always last because it changes the final choice rather than the branch. Two candidates survive? Take the simpler one and revisit only with evidence.
Common misconception: That choosing is about knowing many types. It is about knowing four properties and refusing to add promises nobody uses.
Follow-up: Where does LinkedList survive that process?
When is LinkedList the right answer?+
Rarely: when the workload is dominated by splices at a position you already hold, or as a deque. For index access and iteration it loses to ArrayList; for pure queue and stack duty ArrayDeque beats it.
LinkedList implements both List and Deque, which makes it the universal hammer in examples. In profiles it usually appears as the bottleneck of code that indexes it, and the fix is almost always ArrayList or ArrayDeque.
Common misconception: That LinkedList is the efficient list because linked structures are efficient in textbooks. On modern hardware, cache locality makes the array win at almost everything except end splices.
Follow-up: What does get(i) cost on each of the two?
Why does HashMap iteration order surprise people?+
It is unspecified: it depends on hash codes and capacity. Code that worked with a three-entry map can iterate differently after a resize or a different JDK, so order-sensitive tests turn flaky.
When order is part of the requirement, make it part of the type: LinkedHashMap for insertion order, TreeMap for sorted. Both are drop-in replacements that turn an accidental behaviour into a promise.
Common misconception: That iteration order is stable because it looks stable. Stable-looking and specified are different things.
Follow-up: When is TreeMap worth the O(log n) cost over HashMap?
How do you rank items by count and name, top first?+
A PriorityQueue with a composed comparator: comparingInt(counts::get).reversed().thenComparing(naturalOrder()). Offer everything, poll what you need.
The heap keeps only the next item cheap to find, which is exactly right for top-k: O(log n) per offer and poll, O(1) peek. If the whole collection must end sorted, sort a list instead; if the data keeps arriving, the heap is the structure.
Common misconception: That PriorityQueue iteration is sorted. Only the head is ordered; iterating the heap shows internal arrangement.
Follow-up: Where does the counts map feed in?
What changes when the collection is shared across threads?+
The final answer: ConcurrentHashMap for shared maps, CopyOnWriteArrayList for read-mostly lists, PriorityBlockingQueue or ArrayBlockingQueue for queues, ConcurrentSkipListSet for sorted sets.
The thread-safe answer replaces the type, it does not wrap it: synchronized wrappers make single calls atomic while concurrent collections make compound operations atomic and iterators safe. Choose the concurrent collection at design time, not as a patch after the first race.
Common misconception: That Collections.synchronizedMap is the safe version of HashMap. It is the single-call-safe version; compound logic still races.
Follow-up: Which of these has weakest iteration guarantees, and why is that acceptable?