Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 61 ยท Collections

Maps

Learn Dart maps: literals, reading and updating keys, nullable lookups, putIfAbsent and update, iterating entries, spread and collection for, and key equality rules.

A Map<K, V> stores key-value pairs. You look up a value by its key instead of by position: a user by id, a price by product name, a count by word. Other languages call the same idea a dictionary, hash table or object. Keys are unique; each key points to exactly one value.

The Dart code is read-only. TypeScript stand-ins using Map let you run the same ideas.

Creating maps

A map literal has key: value pairs in braces. Dart infers both type arguments:

DART
void main() {
  var ages = {'Ada': 36, 'Linus': 54};          // Map<String, int>
  var empty = <String, double>{};               // empty map, types spelled out
  Map<int, String> names = {};                  // empty map, types from the variable

  print(ages);            // {Ada: 36, Linus: 54}
  print(ages.length);     // 2
  print(empty.isEmpty);   // true
}

Remember that {} alone is a map, and {1, 2} without colons is a set. The default map is a LinkedHashMap: iterating gives entries in insertion order. Keys can be any type that has a sensible == and hashCode: strings, numbers, enums and records work out of the box.

Other ways to build a map:

DART
void main() {
  var fromPairs = Map.fromEntries([MapEntry('a', 1), MapEntry('b', 2)]);
  var fromLists = Map.fromIterables(['x', 'y'], [10, 20]);
  var squares = {for (var i = 1; i <= 3; i++) i: i * i};   // collection for

  print(fromPairs);   // {a: 1, b: 2}
  print(fromLists);   // {x: 10, y: 20}
  print(squares);     // {1: 1, 2: 4, 3: 9}
}

Reading values: lookups can be null

Square brackets read a value by key. A missing key does not throw. It returns null, so the result type is nullable (V?):

DART
void main() {
  var stock = {'apple': 5, 'pear': 0};

  int? apples = stock['apple'];     // 5
  int? kiwis = stock['kiwi'];       // null: key not present
  print(apples);
  print(kiwis);

  print(stock['kiwi'] ?? 0);        // 0: supply a default
  print(stock['apple']! + 1);       // 6: the ! says "I know it's there"
  print(stock.containsKey('pear')); // true (even though the value is 0)
}

Because of null safety (see Null Safety), you must handle the null case before using the value as a plain int. Use ?? for a default, a null check, or ! only when you are certain. containsKey matters when null is itself a legal value, since m[k] == null cannot tell "missing" from "stored null".

Adding, updating and removing

Assigning to a key adds the pair or overwrites the old value:

DART
void main() {
  var scores = <String, int>{};

  scores['ada'] = 10;                      // add
  scores['ada'] = 12;                      // overwrite
  scores.addAll({'bob': 7, 'cy': 9});      // add many
  scores.remove('cy');                     // returns the removed value (9)
  scores.removeWhere((k, v) => v < 8);     // drops bob
  print(scores);                           // {ada: 12}
}

The following methods avoid the "read, check null, write" dance:

DART
void main() {
  var counts = <String, int>{};

  // putIfAbsent: only runs the function when the key is missing; returns the value
  counts.putIfAbsent('dart', () => 0);

  // update: change an existing value; ifAbsent handles a missing key
  counts.update('dart', (n) => n + 1);
  counts.update('flutter', (n) => n + 1, ifAbsent: () => 1);

  // ??= assigns only when the current value is null
  counts['web'] ??= 100;

  print(counts);   // {dart: 1, flutter: 1, web: 100}

  // grouping: one list per key, created on demand
  var groups = <int, List<String>>{};
  for (var word in ['an', 'ox', 'cat', 'dog', 'eagle']) {
    groups.putIfAbsent(word.length, () => []).add(word);
  }
  print(groups);   // {2: [an, ox], 3: [cat, dog], 5: [eagle]}
}

update on a missing key without ifAbsent throws an ArgumentError, so supply ifAbsent whenever the key might not exist. Counting with update(k, (n) => n + 1, ifAbsent: () => 1) and grouping with putIfAbsent(k, () => []).add(x) are two patterns worth memorising.

TypeScript Counting and grouping (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.

Iterating over a map

A map is not itself an Iterable, but it exposes three views: keys, values and entries.

DART
void main() {
  var prices = {'tea': 2.5, 'coffee': 3.0, 'milk': 1.2};

  for (var key in prices.keys) {
    print(key);
  }

  for (var entry in prices.entries) {
    print('${entry.key} costs ${entry.value}');
  }

  // Dart 3: destructure each entry with an object pattern
  for (var MapEntry(:key, :value) in prices.entries) {
    print('$key -> $value');
  }

  prices.forEach((name, price) => print('$name: $price'));

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

keys and values are lazy iterables (a view over the map), so use .toList() for a snapshot. Do not add or remove keys while you loop over the map, or Dart throws a ConcurrentModificationError; changing the values of existing keys is fine.

flowchart LR
    M["prices map"] --> K["keys<br/>tea, coffee, milk"]
    M --> V["values<br/>2.5, 3.0, 1.2"]
    M --> E["entries<br/>MapEntry pairs"]
    E --> P["entry.key<br/>entry.value"]

A map offers three views over the same data: its keys, its values and its key-value entries.

Transforming maps

map on a map turns each pair into a new MapEntry, building a new map. Spread and collection if/for work inside map literals too:

DART
void main() {
  var prices = {'tea': 2.5, 'coffee': 3.0};

  var cents = prices.map((k, v) => MapEntry(k, (v * 100).round()));
  print(cents);   // {tea: 250, coffee: 300}

  var defaults = {'theme': 'light', 'lang': 'en'};
  var user = {'lang': 'fr'};
  var settings = {...defaults, ...user, if (user.isEmpty) 'guest': 'yes'};
  print(settings);   // {theme: light, lang: fr}: later keys win
}

When keys repeat in a spread, the later value overwrites the earlier one, which makes {...defaults, ...overrides} the standard way to merge settings. Spreading creates a new map, so neither defaults nor user changes.

TypeScript Merging and transforming (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.

Keys, equality and sorted maps

A map finds keys with == and hashCode, just like a set. Strings and numbers behave as you expect. A class that does not override == uses identity, so map[Point(1, 2)] will not find a value stored under a different Point(1, 2) object. Records and enums are safe keys.

If you want the keys sorted, use SplayTreeMap from dart:collection; HashMap gives up ordering for a bit less memory. A const map literal is unmodifiable, and Map.unmodifiable(other) makes a read-only copy.

DART
import 'dart:collection';

void main() {
  var sorted = SplayTreeMap<String, int>()..addAll({'pear': 2, 'apple': 5, 'fig': 1});
  print(sorted);            // {apple: 5, fig: 1, pear: 2}
  print(sorted.firstKey()); // apple
}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does m['missing'] return when the key is not in Map<String, int> m?

    A missing key gives null, so the expression has the type int?. Use ?? for a default or check containsKey first.
  2. 2. What does putIfAbsent('a', () => 1) do when 'a' already exists?

    The function runs only if the key is missing. For an existing key the map is unchanged and the current value is returned.
  3. 3. Which code counts a word whether or not it was seen before?

    update without ifAbsent throws for a missing key. counts[w]++ fails because the lookup is nullable, and Map has no add method.
  4. 4. In {...a, ...b}, which value wins for a key that appears in both maps?

    Later entries overwrite earlier ones, so b's value wins. That is why spread is used to merge overrides onto defaults.

Summary

  • A Map<K, V> holds unique keys; the literal {k: v} keeps insertion order.
  • m[key] returns V?: handle null with ??, a check or !; use containsKey when null is a valid value.
  • putIfAbsent, update(... ifAbsent:) and ??= are the safe ways to add or change values.
  • Iterate with keys, values or entries; do not add or remove keys during the loop.
  • map((k, v) => MapEntry(...)), spread and collection if/for build new maps; later keys win in a spread.
  • Keys follow == and hashCode; SplayTreeMap gives sorted keys.

Next, transform collections with Iterables and Functional Collection Methods.