Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 61 ยท Collections

Iterables and Functional Collection Methods

Learn Dart Iterable methods: map, where, fold, reduce, expand, any, every, take and skip, why they are lazy, and when to call toList to get a real collection.

Lists, sets and the keys of a map all share one parent type: Iterable<E>. An iterable is anything you can walk through one element at a time, and it comes with a toolbox of methods that transform, filter, combine and test its elements. This is the functional style of programming: instead of writing a loop with a counter and a temporary list, you describe what you want (where, map, fold) and let the collection do the work.

There is one idea you must understand to use these methods well: most of them are lazy. They do not compute anything until something asks for the elements. This lesson shows the everyday methods first, then what lazy means in practice. The Dart code is read-only; TypeScript stand-ins let you run the matching ideas.

Transforming and filtering

map turns every element into something else; where keeps the elements that pass a test. Both take a function:

DART
void main() {
  var numbers = [1, 2, 3, 4, 5, 6];

  var doubled = numbers.map((n) => n * 2);
  var evens = numbers.where((n) => n.isEven);

  print(doubled);          // (2, 4, 6, 8, 10, 12)
  print(evens.toList());   // [2, 4, 6]
}

Notice the parentheses in the first output. Printing a lazy iterable shows round brackets, not the square brackets of a list. That is a quick visual clue that you still have an iterable and not a list.

Methods chain from left to right, so a pipeline reads like a sentence:

DART
void main() {
  var words = ['apple', 'fig', 'banana', 'kiwi', 'cherry'];

  var result = words
      .where((w) => w.length > 3)
      .map((w) => w.toUpperCase())
      .toList();

  print(result);   // [APPLE, BANANA, KIWI, CHERRY]
}

Other selection methods: take(n) and skip(n) keep or drop the first n; takeWhile and skipWhile do so while a condition holds; whereType<T>() keeps only elements of a type; followedBy(other) appends another iterable.

Combining many values into one

fold takes a starting value and a function that merges the running result with each element. It works for sums, products, building strings or maps, and the starting value also decides the result type:

DART
void main() {
  var prices = [4.5, 3.0, 2.5];

  var total = prices.fold(0.0, (sum, p) => sum + p);
  print(total);   // 10.0

  var sentence = ['a', 'b', 'c'].fold('', (acc, s) => acc.isEmpty ? s : '$acc-$s');
  print(sentence);   // a-b-c

  var longest = ['pear', 'banana', 'fig']
      .reduce((a, b) => a.length >= b.length ? a : b);
  print(longest);    // banana
}

reduce is fold without a starting value: it uses the first element as the start, so the result has the element type, and it throws a StateError on an empty iterable. Prefer fold when the collection might be empty or when the result type differs from the element type. Dart's core library has no sum method on iterables. Use fold, or sum from package:collection.

flowchart LR
    S["start: 0.0"] --> A["+ 4.5"]
    A --> B["+ 3.0"]
    B --> C["+ 2.5"]
    C --> R["result: 10.0"]

fold carries a running result through the elements, one step at a time.

TypeScript map, filter, fold (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Flattening with expand

expand replaces each element with zero or more elements and joins the results into one flat iterable. It is what other languages call flatMap:

DART
void main() {
  var teams = [
    ['Ada', 'Linus'],
    ['Grace'],
    <String>[],
  ];

  print(teams.expand((members) => members).toList());   // [Ada, Linus, Grace]

  var pairs = [1, 2, 3].expand((n) => [n, n * 10]).toList();
  print(pairs);   // [1, 10, 2, 20, 3, 30]
}

Asking questions about the elements

A group of methods returns a single answer instead of a new iterable:

DART
void main() {
  var ages = [12, 19, 34, 8];

  print(ages.any((a) => a >= 18));      // true: at least one adult
  print(ages.every((a) => a >= 18));    // false: not everyone
  print(ages.contains(34));             // true
  print(ages.firstWhere((a) => a > 15));              // 19
  print(ages.firstWhere((a) => a > 99, orElse: () => -1)); // -1
  print(ages.indexWhere((a) => a < 10));              // 3
  print(ages.length);                                  // 4
  print(ages.isEmpty);                                 // false
}

firstWhere throws a StateError when nothing matches unless you pass orElse. lastWhere searches from the end, and singleWhere expects exactly one match and throws if there are none or several. Dart 3 also provides firstOrNull, lastOrNull and singleOrNull, which return null instead of throwing.

Lazy iterables

Here is the idea promised earlier. map, where, take, skip, expand and followedBy do not produce a list. They return a lightweight object that remembers how to produce the elements. The work happens each time you iterate, and only as far as you iterate:

DART
void main() {
  var squares = [1, 2, 3, 4].map((n) {
    print('computing $n');
    return n * n;
  });

  print('nothing computed yet');
  print(squares.first);   // computes only 1
  print(squares.first);   // computes 1 again!
  print(squares.toList()); // computes all four
}
TEXT
nothing computed yet
computing 1
1
computing 1
1
computing 1
computing 2
computing 3
computing 4
[1, 4, 9, 16]

Two lessons follow from the output:

  1. Laziness saves work. Asking for first computed one element, not four. Combined with take, you can even work through an infinite sequence.
  2. Repeated iteration repeats the work. Every pass through squares runs the function again. If the function is slow or has side effects, call .toList() (or .toSet()) once and reuse the result.
flowchart LR
    L["list: 1, 2, 3, 4"] --> M["map: n * n<br/>(lazy)"]
    M --> W["where: n > 4<br/>(lazy)"]
    W --> T["toList()<br/>runs the pipeline"]
    T --> R["[9, 16]"]

Nothing runs until the pipeline reaches a method like toList, first, length or a for-in loop.

Also remember that length on a lazy where result has to walk through all of it, and that a lazy view reflects later changes to its source list. A common bug is keeping list.where(...) in a field, then wondering why it changes when the list changes.

TypeScript Seeing laziness with generators (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Converting back to collections

Use toList() for a list (growable unless you pass growable: false), toSet() for a set, and join(', ') to turn the elements into a string. Maps come from Map.fromEntries(iterable) or by building a map literal with collection for:

DART
void main() {
  var names = ['ada', 'linus', 'grace'];

  var lengths = {for (var n in names) n: n.length};
  print(lengths);                 // {ada: 3, linus: 5, grace: 5}

  var byFirstLetter = Map.fromEntries(names.map((n) => MapEntry(n[0], n)));
  print(byFirstLetter);           // {a: ada, l: linus, g: grace}

  print(names.map((n) => n.toUpperCase()).join(', '));   // ADA, LINUS, GRACE
}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does [1, 2, 3].map((n) => n * 2) evaluate to?

    map returns a lazy Iterable, which prints with round brackets. Call toList() when you need a real list.
  2. 2. A function passed to map prints a message. How often does it run if you iterate the result twice without calling toList?

    A lazy iterable recomputes on every pass. Convert it once with toList() or toSet() if the work is expensive or has side effects.
  3. 3. Which method fails with a StateError on an empty list?

    reduce uses the first element as its start, so an empty iterable has nothing to start from. fold has an explicit starting value, and any and every simply return false and true.
  4. 4. What does [[1, 2], [3]].expand((x) => x).toList() return?

    expand flattens: each inner list is replaced by its elements, and the results are joined in order.

Summary

  • List, Set and map views are all Iterables with the same methods.
  • map transforms, where filters, take/skip slice, expand flattens, whereType filters by type.
  • fold combines elements with a starting value; reduce uses the first element and fails on empty input.
  • any, every, firstWhere (with orElse), indexWhere and contains answer questions.
  • Most methods are lazy and rerun on every pass; call toList() or toSet() once to get a real collection.

Next, meet the specialised collections in The dart:collection Library, then write code that works for many types at once with Generics.