Sub topic 14
Choosing the Right Collection
This chapter assumes you know the basics of Dart lists, maps, and sets. It also assumes you are comfortable with generics such as List<int>, and with nullable types such as int?. It builds on the earlier chapters about equality and hashCode, and about ordering guarantees.
By the end, you should be able to look at a problem and pick List, Map, or Set for reasons you can explain, not by habit.
Start from the question you ask the data
Each collection answers one kind of question well. Choose by the question your code asks most often.
| Your code asks | Best fit | Why |
|---|---|---|
| What is the third item? What comes after this one? | `List` | Elements have a position, and indexing is constant time. |
| What is the value for this key? | `Map` | Lookup by key is a hash lookup, not a scan. |
| Have I seen this before? Is this allowed? | `Set` | Membership checks are fast, and duplicates are impossible. |
| Which items are in both groups, or in only one? | `Set` | `intersection`, `union`, and `difference` are built in. |
| What order did these arrive in, with repeats kept? | `List` | Only a list keeps duplicates and position. |
The table lists the common cases. The sections below explain the reasoning and the exceptions.
Cost matters once data grows
For a handful of items, any collection works. With thousands of items, the cost of the operation you repeat the most starts to matter. The default Map and Set literals use hash tables, so their lookups take constant time on average. A List has to scan.
| Operation | `List` | `Map` / `Set` (default) |
|---|---|---|
| Read by index | constant | not available |
| Read by key or check membership | linear (`contains`, `indexOf`) | constant on average |
| Add at the end | constant, amortized | constant on average |
| Insert or remove at the front or middle | linear, because later items shift | not applicable |
| Iterate all | linear | linear |
A common mistake is calling contains on a large list inside a loop. That makes the whole loop quadratic. Converting the list to a set once removes the problem.
void main() {
final allowedList = ['ann', 'bob', 'cy'];
final allowedSet = {'ann', 'bob', 'cy'};
print(allowedList.contains('bob')); // true, scans elements one by one
print(allowedSet.contains('bob')); // true, hash lookup
}With three names the difference is invisible. With 100,000 names checked 100,000 times, it is the difference between instant and noticeably slow.
Use a Set when uniqueness is the rule
A Set is the right choice when a duplicate would be a bug. Examples are the IDs you have already processed, the tags on an item, or the cells a search has visited. The add method returns false for an element that was already there, so you can combine the check and the insert in one call.
void main() {
final seen = <int>{};
for (final id in [4, 8, 4, 15, 8]) {
if (seen.add(id)) {
print('first time: $id');
} else {
print('skip duplicate: $id');
}
}
}To remove duplicates from a list while keeping first-seen order, convert to a set and back. The default set is insertion-ordered, so the order survives.
void main() {
final raw = ['b', 'a', 'b', 'c', 'a'];
final unique = raw.toSet().toList();
print(unique); // [b, a, c]
}Use a List instead when repeats carry meaning. A shopping cart with two of the same item, or a log of events, should keep every entry.
Use a Map when you look things up by key
If you find yourself writing a loop with firstWhere to find a record by its ID, you probably want a Map. Build it once, then look up directly.
Maps also suit grouping. A map from a key to a list of values is a common shape, and putIfAbsent creates the list the first time a key appears.
void main() {
final words = ['apple', 'avocado', 'banana', 'blueberry', 'cherry'];
final byLetter = <String, List<String>>{};
for (final w in words) {
byLetter.putIfAbsent(w[0], () => []).add(w);
}
print(byLetter);
// {a: [apple, avocado], b: [banana, blueberry], c: [cherry]}
}Remember that a map lookup returns a nullable value. Decide up front what a missing key means: a default with ??, an error, or a branch for "not found". If every key must be present, that is a hint your data may fit a class with named fields better than a map.
Equality decides whether a Set or Map behaves as you expect
Sets and map keys rely on == and hashCode. Two objects that look the same are different keys unless the class says they are equal. Built-in types such as int, String, and bool already do this. Lists, maps, and sets do not. They compare by identity.
class Point {
final int x;
final int y;
const Point(this.x, this.y);
@override
bool operator ==(Object other) =>
other is Point && other.x == x && other.y == y;
@override
int get hashCode => Object.hash(x, y);
}
void main() {
final visited = <Point>{};
visited.add(Point(0, 0));
print(visited.contains(Point(0, 0))); // true, equal by value
final byList = <List<int>, String>{
[1, 2]: 'a',
};
print(byList[[1, 2]]); // null, a new list is a different key
}Two practical rules follow from this:
- If a class goes into a
Setor is used as a map key, override both==andhashCode, and keep them consistent. Equal objects must have equal hash codes. - Do not use a list as a key unless you hold on to the same list object. Use a string, a number, or a small class with value equality instead.
Ordering: a hidden requirement
Ask whether order matters to the result, and what kind of order you mean.
- Position order. Only a
Listgives you index access. If you need "the item at position 2", use a list. - Insertion order. Map and set literals, and the default
Map()andSet()constructors, iterate in insertion order. You can rely on this for display, but it is not a substitute for a sorted structure. - Sorted order. If you need keys or elements kept sorted as you add them, use
SplayTreeMaporSplayTreeSetfromdart:collection. Lookups there cost logarithmic time instead of constant, so only choose them when you need the order.
If you sort only once, at the end, sorting a list is usually simpler and faster than keeping a sorted structure the whole time.
Combining collections
Real programs often use more than one collection for the same data. A pattern worth knowing is keeping a List for display order and a Set or Map for fast checks.
void main() {
final order = <String>[]; // display order, keeps position
final index = <String, int>{}; // name -> position, for fast lookup
for (final name in ['ann', 'bob', 'cy']) {
index[name] = order.length;
order.add(name);
}
print(order); // [ann, bob, cy]
print(index['cy']); // 2
print(index['dee']); // null
}The cost is that you must keep both in sync. If you remove an item from the list, shifting positions makes the stored indexes wrong. Use this pattern only when the data changes rarely, or wrap both structures in one class so every change goes through a single place.
Mutability and exposure
When a class owns a collection, think about who can change it. Returning the internal list lets callers add or remove items behind your back. Return List.unmodifiable(items) or an Iterable<T> when callers should only read. The mutability chapter covers the details. For design, the rule is to choose the narrowest type you can expose. Iterable for "just loop over it", Set when uniqueness is part of the contract, and List only when position matters to the caller.
Quick checklist
- Is each item found by a key? Use a
Map. - Is uniqueness required, or are you mostly asking "is it in there"? Use a
Set. - Does position or repetition matter? Use a
List. - Will the items be keys or set members? Check that
==andhashCodeare defined. - Do you need sorted order maintained continuously? Consider
SplayTreeMaporSplayTreeSet. Otherwise sort a list once. - Are you scanning a large list repeatedly? Build a
SetorMapfirst.
Exercise
A function receives a list of 50,000 user IDs and must keep only those that also appear in a list of 20,000 blocked IDs. The current code calls blocked.contains(id) on the list for every ID. What collection should replace blocked, and why?
Show answer
Use a Set<int>, built once with blocked.toSet(). Set.contains is a hash lookup (constant time on average), while List.contains scans, so the original loop does up to 50,000 × 20,000 comparisons. With a set, each check is one lookup. You could also call ids.where((id) => !blockedSet.contains(id)) to filter lazily.
Exercise
You store Point objects, a class with final int x, y and no == or hashCode override, in a Set<Point>. You add Point(1, 2) twice and the set has length 2. Why, and what is the fix?
Show answer
Without overrides, Point uses identity equality, so two separately created objects are never equal. The set sees two different elements. Override operator == to compare x and y, and override hashCode with Object.hash(x, y). Then the second add returns false and the length stays 1.
Exercise
You need to count how many times each word appears in a list of words, and then print the words in the order they were first seen. Which collections would you use?
Show answer
Use a Map<String, int> for the counts, for example counts[w] = (counts[w] ?? 0) + 1. Map literals iterate in insertion order, so iterating counts.entries gives words in first-seen order. A list alone would need a scan for every word, and a set cannot hold counts.