Sub topic 8
Transforming data: where, map, fold, and toList
This chapter assumes you can read Dart generics such as List<int>, write closures like (n) => n * 2, and have seen for-in loops over lists. You will learn how where, map, fold, and toList fit together, why most of them are lazy, and which mistakes they cause most often.
The Iterable pipeline
List, Set, and a map's keys and values are all Iterables, so they share the transformation methods in this chapter. Most of these methods return a new Iterable and leave the original collection unchanged.
| Method | Purpose | Returns |
|---|---|---|
| `where(test)` | Keep elements for which `test` is true | lazy `Iterable<E>` |
| `map(f)` | Convert each element with `f` | lazy `Iterable<T>` |
| `expand(f)` | Convert each element into zero or more elements and flatten | lazy `Iterable<T>` |
| `take(n)`, `skip(n)` | Keep or drop the first `n` elements | lazy `Iterable<E>` |
| `whereType<T>()` | Keep only elements of type `T` | lazy `Iterable<T>` |
| `fold(initial, combine)` | Reduce to one value of any type | the final value |
| `reduce(combine)` | Reduce to one value of the element type | the final value |
| `toList()`, `toSet()` | Run the pipeline and store the results | `List<E>`, `Set<E>` |
where and map
where filters and map converts. Chain them, then finish with toList.
void main() {
final nums = [5, 3, 8, 1, 9, 2];
final result = nums
.where((n) => n.isEven)
.map((n) => n * n)
.toList();
print(result); // [64, 4]
print(nums); // [5, 3, 8, 1, 9, 2], the source is unchanged
}The closure passed to where must return a bool. The type of the closure passed to map decides the element type of the result. Here map produces an Iterable<int>. If the closure returned a String, you would get an Iterable<String>.
You can also convert to a different type:
void main() {
final ids = [101, 102, 103];
final labels = ids.map((id) => 'item-$id').toList();
print(labels); // [item-101, item-102, item-103]
}Lazy evaluation
where, map, expand, take, and skip do not compute anything when you call them. They return a view that computes elements when something iterates over it. The next example counts how often the closure runs.
void main() {
final nums = [1, 2, 3, 4];
var calls = 0;
final doubled = nums.map((n) {
calls++;
return n * 2;
});
print(calls); // 0, nothing has run yet
print(doubled.toList()); // [2, 4, 6, 8]
print(calls); // 4
doubled.toList();
print(calls); // 8, each iteration runs the closure again
}This has three consequences.
- Repeated work. If you iterate a lazy iterable several times, the closure runs each time. If the closure is expensive, call
toList()once and reuse the list. - Late reads of the source. A lazy iterable reads the source collection when it is iterated, not when it was created.
- Skipped side effects. Code inside
mapthat you rely on, such as logging, never runs if nobody iterates the result.
The second consequence is easy to demonstrate:
void main() {
final nums = [1, 2, 3];
final big = nums.where((n) => n > 1);
nums.add(4);
print(big.toList()); // [2, 3, 4], includes the element added later
}toList() is the point where results are fixed. After it runs, the new list no longer depends on the source.
Laziness helps with early exit
Because elements are pulled one at a time, methods that stop early avoid unnecessary work. first, take, any, and firstWhere stop as soon as they have their answer.
void main() {
final nums = [1, 2, 3, 4, 5, 6];
var checked = 0;
final firstTwoEvens = nums
.where((n) {
checked++;
return n.isEven;
})
.take(2)
.toList();
print(firstTwoEvens); // [2, 4]
print(checked); // 4, elements 5 and 6 were never tested
}fold and reduce
fold walks the elements and carries an accumulator. You supply the starting value and a function that takes the accumulator and the next element and returns the new accumulator.
void main() {
final nums = [5, 3, 8, 1, 9, 2];
final total = nums.fold<int>(0, (sum, n) => sum + n);
print(total); // 28
}The accumulator can have a different type from the elements. This example counts words by length:
void main() {
final words = ['a', 'bb', 'cc', 'd'];
final byLength = words.fold<Map<int, int>>({}, (acc, w) {
acc[w.length] = (acc[w.length] ?? 0) + 1;
return acc;
});
print(byLength); // {1: 2, 2: 2}
}Always write the type argument, as in fold<int>. Without it, Dart infers the type from the initial value, and a mismatch can fail. For example, fold(0, ...) over a list of double may infer int, and then sum + n is a double where an int is required. Writing fold<double>(0.0, ...) avoids that.
reduce is shorter but stricter. It uses the first element as the starting value, so the result must have the element type, and it throws a StateError on an empty iterable.
void main() {
print([4, 9, 2].reduce((a, b) => a > b ? a : b)); // 9
try {
<int>[].reduce((a, b) => a + b);
} on StateError {
print('reduce needs at least one element');
}
print(<int>[].fold<int>(0, (a, b) => a + b)); // 0, fold handles empty input
}Use fold when the input might be empty or the result type differs. Use reduce only when emptiness is impossible or should be an error.
Other useful steps
expandflattens:[[1, 2], [3]].expand((l) => l).toList()gives[1, 2, 3].whereType<T>()filters by type and narrows the static type.anyandeveryreturn abool.anyis true if at least one element passes, andeveryis true only if all pass.firstWherereturns the first match and throwsStateErrorif none exists, unless you passorElse.
void main() {
final mixed = <Object>[1, 'a', 2.5, 3];
final ints = mixed.whereType<int>().toList();
print(ints); // [1, 3]
final nums = [5, 3, 8];
print(nums.any((n) => n > 7)); // true
print(nums.every((n) => n > 4)); // false
print(nums.firstWhere((n) => n > 100, orElse: () => -1)); // -1
}Transforming maps
A Map is not an Iterable, but its keys, values, and entries are. To filter or convert a map, work on entries and rebuild a map from the result.
void main() {
final prices = {'apple': 3, 'pear': 5, 'fig': 8};
final expensive = Map.fromEntries(
prices.entries.where((e) => e.value > 4),
);
print(expensive); // {pear: 5, fig: 8}
final doubled = prices.map((k, v) => MapEntry(k, v * 2));
print(doubled); // {apple: 6, pear: 10, fig: 16}
final longNames = prices.keys.where((k) => k.length > 3).toList();
print(longNames); // [apple, pear]
}Map.map is different from Iterable.map. It is eager, it returns a new Map, and its closure must return a MapEntry. To change a map in place, use removeWhere or updateAll.
toList, toSet, and growable results
toList() returns a growable list by default. Pass growable: false for a fixed-length list. toSet() removes duplicates, using == and hashCode.
void main() {
final nums = [1, 2, 2, 3, 3, 3];
final unique = nums.map((n) => n * 10).toSet();
print(unique); // {10, 20, 30}
final fixed = nums.where((n) => n > 1).toList(growable: false);
try {
fixed.add(4);
} on UnsupportedError {
print('fixed-length list cannot grow');
}
}Common errors
- Treating the result as a list.
List<int> r = nums.where(...)does not compile becausewherereturns anIterable<int>. Add.toList(). - Printing an unevaluated iterable.
print(nums.where((n) => n > 1))shows(2, 3)in parentheses. That is an iterable, not a list. Parentheses in output are the sign. - Side effects in
map. Usingmapto call a function for its effect does nothing until the result is iterated. Use afor-inloop orforEachinstead. - Recomputing expensive pipelines. Each pass over a lazy iterable repeats the work. Call
toList()once. - Changing the source while iterating. Modifying the source list while a pipeline is iterating over it throws
ConcurrentModificationError. - Omitting
fold's type argument. This is covered above. Writefold<T>.
Exercise
Given final orders = [12, 0, 7, 30, 5];, write an expression that returns the sum of all order values greater than 5, using where and fold, and say what it returns. Then explain what orders.where((o) => o > 5) alone gives you if you print it.
Show answer
orders.where((o) => o > 5).fold<int>(0, (sum, o) => sum + o) returns 49 (12 + 7 + 30). Printing orders.where((o) => o > 5) alone shows (12, 7, 30). That is a lazy Iterable, not a List, and it re-runs the test each time it is iterated. Call .toList() if you need a stored list.
Exercise
A closure passed to map increments a counter. You iterate the resulting iterable twice with toList(). The source has 3 elements. What is the counter afterwards, and how do you make it 3?
Show answer
The counter is 6, because the lazy iterable runs the closure on every iteration. Call toList() once, store the list in a variable, and iterate that list instead. The counter is then 3.