CodeBlanks Logo Icon CodeBlanks

Map iteration

Learn to iterate over Maps with for-in and forEach.

Iterating a Map

Several ways exist to walk a Map. The first is forEach: ages.forEach((k, v) => print('$k: $v'));. It yields the key and the value in order.

The second is for-in over entries: for (var e in ages.entries) { print(e.key); }. Each e is a MapEntry with .key and .value fields.

To walk only keys or values, use ages.keys or ages.values. A Map keeps the insertion order, so the iteration order is predictable.

entries and keys

entries yields each pair as a MapEntry with .key and .value fields. keys returns only the keys, values only the values.

For example for (var k in ages.keys) print(k); writes each key on a new line. for (var v in ages.values) print(v); writes the values.

When the order of work matters, entries is handier; if you only care about one side, keys or values is a shortcut.

Practice Print the ages

Create a Map<String, int> with two people. Use forEach to print each pair as $key: $value.

Starter code

main.dart
void main() {
  var ages = <String, int>{};
  // add two pairs

  // forEach to print
}

Sample solution

main.dart
void main() {
  var ages = <String, int>{};
  ages['Ayşe'] = 28;
  ages['Mert'] = 31;
  ages.forEach((k, v) => print('$k: $v'));
}

Expected output

Ayşe: 28
Mert: 31

Questions and answers

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

1 Match the iteration ways

Term Meaning
forEach Callback per pair
entries List of MapEntry
keys Only keys
values Only values

2 What is the forEach signature?

  • (k, v) => ... Correct answer
  • (k) => ...
  • (v) => ...
  • (e) => ...

Explanation: Map.forEach takes two parameters: key and value.

3 The for-in loop

Question
void main() {
  var ages = <String, int>{'Ayşe': 28};
  for (var e in ages.____) {
    print(e.key);
  }
}
Answer
void main() {
  var ages = <String, int>{'Ayşe': 28};
  for (var e in ages.entries) {
    print(e.key);
  }
}

Explanation: entries yields each pair as a MapEntry.

All lessons in Beginner