Dart Collection Aggregation
Aggregation combines all the values in a collection into a single value. A total, a count, and a product are all aggregations.
Summing with fold
The fold call starts the sum at zero. Each step adds the next number to the running sum.
void main() {
var numbers = [1, 2, 3, 4];
var total = numbers.fold<int>(0, (sum, n) => sum + n);
print(total);
}Multiplying with fold
The same shape multiplies when the start value is one. Each step multiplies the running product by the next number.
void main() {
var numbers = [2, 3, 4];
var product = numbers.fold<int>(1, (prod, n) => prod * n);
print(product);
}Summing with reduce
The list is guaranteed to hold values, so reduce is safe here. The first value starts the sum and each later value joins it.
void main() {
var numbers = [4, 5, 6];
var total = numbers.reduce((a, b) => a + b);
print(total);
}Summing with a plain loop
A loop with a running variable reaches the same total. The loop spells out every step that fold hides.
void main() {
var numbers = [1, 2, 3, 4];
var total = 0;
for (var n in numbers) {
total = total + n;
}
print(total);
}Counting with fold
The combine function ignores each value and adds one instead. The result is the number of elements in the list.
void main() {
var words = ['oak', 'elm', 'ash', 'yew'];
var count = words.fold<int>(0, (count, word) => count + 1);
print(count);
}Example
void main() {
var scores = [7, 9, 5];
var total = scores.fold<int>(0, (sum, n) => sum + n);
var best = scores.reduce((a, b) => a > b ? a : b);
print(total);
print(best);
}Key points
- The fold method starts from an initial value and combines it with each element in turn.
- Fold takes a type argument, as in fold<int>, so the running value has a known type.
- The combine function receives the running value and the next element.
- The reduce method combines elements without an initial value.
- Reduce needs at least one element, because the first element becomes the starting value.
- A plain loop can compute the same total with an explicit running variable.
In this example, fold adds the three scores into a total of 21. The reduce call keeps the larger of each pair it compares. The largest score, 9, is the final running value.
Note
fold also counts, by adding one for each element it visits.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
Why does the summing example write fold<int> instead of plain fold?