CodeBlanks Logo Icon CodeBlanks

Summary - Collection methods

Combine map, where and fold to write a sales report.

Summary - Collection methods

In this group we learned five core collection methods: map transforms, where filters, fold/reduce reduces to one value, forEach does side effects, any/every query.

These methods work through Iterable and use lazy evaluation. They are chainable; for example list.where(...).map(...).fold(...) processes data in one flow.

Now let's do an exercise that uses three methods together: double numbers, filter evens and sum them.

Practice Combine three methods

Chain on the list [1, 2, 3, 4, 5]: first double with map((n) => n * 2), then filter those greater than 5 with where((n) => n > 5), finally sum with fold(0, (acc, n) => acc + n). Print the result.

Starter code

main.dart
void main() {
  var numbers = [1, 2, 3, 4, 5];
  // double with .map, filter >5 with .where, sum with .fold
  // print the result
}

Sample solution

main.dart
void main() {
  var numbers = [1, 2, 3, 4, 5];
  var result = numbers.map((n) => n * 2).where((n) => n > 5).fold(0, (acc, n) => acc + n);
  print(result);
}

Expected output

24

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match methods to their purpose

Term Meaning
map Transform
where Filter
fold Reduce to one value
forEach Side effect

2 Which method reduces to a single value?

  • map
  • forEach
  • where
  • fold Correct answer

Explanation: fold reduces a collection to a single value.

All lessons in Intermediate