Choosing List vs Set vs Map
By the end of this lesson, you'll be able to:
- Apply a clear decision process for picking the right collection type
- Justify a collection choice for a given real scenario
- Recognize signals in a problem description that point toward one type over another
Prerequisites: "Nested Collections"
The decision process
Ask these questions in order:
- Do I need to look things up by a key? →
Map. - Do duplicates need to be automatically prevented, and order doesn't matter? →
Set. - Otherwise — order matters, and duplicates are fine (or irrelevant)? →
List.
Most real scenarios answer clearly with the first matching question — you rarely need to weigh all three carefully.
Working through real scenarios
- "Store every Order for a customer, in the order they were placed." → List (order matters, duplicates like two identical orders are fine).
- "Track which product categories appear at least once across all orders." → Set (only uniqueness matters, order doesn't).
- "Look up a Customer's discount tier by their Customer Id." → Map (a direct key-based lookup).
- "Group every Order by which Customer placed it." → Map of Lists, from the previous lesson (a key — Customer Id — mapping to a collection of values).
When more than one type would technically work
// Works, but obscures intent
List<String> processedOrderIds = new List<String>();
if (! processedOrderIds.contains(orderId)) {
processedOrderIds.add(orderId);
}
// Clearer: the Set itself communicates "these must be unique"
Set<String> processedOrderIds = new Set<String>();
processedOrderIds.add(orderId); // duplicates handled automatically
Both versions technically prevent duplicates, but the Set version is shorter, faster, and — importantly — the type itself documents the intent ("this must never contain duplicates") without needing a comment to explain it.
Exercise
As comments, choose List, Set, or Map for each: (1) storing a shopping cart's items in the order added, (2) tracking unique visitor IP addresses to a page, (3) looking up a Product's price by its SKU.
Show hint
Apply the three-question decision process to each.
Choosing List vs Set vs Map Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A short decision process turns "which collection do I need?" from a guess into a quick, confident choice, based on what the problem actually asks for.