Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Dart notes · Topic 8 of 19 · 5 min read

Dart maps and sets

Dart maps and sets notes with examples: reading and updating entries, looping over keys and entries, counting, sets, union and intersection, JSON-like data.

What is a map?

A Map stores key-value pairs. You look up a value by its key, like a word in a dictionary or a phone number by a name. Keys are unique; values may repeat.

void main() {
  Map<String, int> marks = {
    'Asha': 88,
    'Rohit': 74,
    'Meena': 91,
  };
  print(marks);
  print(marks['Asha']);
  print(marks['Ravi']);
  print(marks.length);
}
{Asha: 88, Rohit: 74, Meena: 91}
88
null
3

Map<String, int> means the keys are Strings and the values are ints. Looking up a key that is not there gives null, so marks['Asha'] has the type int? (see the Null Safety topic).

Adding, updating and removing

void main() {
  var stock = <String, int>{'Pen': 40, 'Pencil': 25};
  stock['Eraser'] = 10;                    // add
  stock['Pen'] = 35;                       // update
  stock.update('Pencil', (v) => v + 5);    // update from the old value
  stock.putIfAbsent('Scale', () => 15);    // add only if missing
  stock.putIfAbsent('Pen', () => 99);      // Pen exists: no change
  stock.remove('Eraser');
  print(stock);
  print(stock.containsKey('Pen'));
  print(stock.containsValue(15));
}
{Pen: 35, Pencil: 30, Scale: 15}
true
true

Looping over a map

void main() {
  var fees = {'Maths': 1200, 'Science': 1500, 'English': 900};
  for (var subject in fees.keys) {
    print(subject);
  }
  print(fees.values.reduce((a, b) => a + b));
  for (var e in fees.entries) {
    print('${e.key}: Rs ${e.value}');
  }
  fees.forEach((k, v) => print('$k -> $v'));
}
Maths
Science
English
3600
Maths: Rs 1200
Science: Rs 1500
English: Rs 900
Maths -> 1200
Science -> 1500
English -> 900

Dart's default map (a LinkedHashMap) remembers the order in which keys were added.

Counting with a map

Counting how often each item appears is one of the most common uses of a map:

void main() {
  var votes = ['A', 'B', 'A', 'C', 'A', 'B'];
  var count = <String, int>{};
  for (var v in votes) {
    count[v] = (count[v] ?? 0) + 1;
  }
  print(count);
}
{A: 3, B: 2, C: 1}

count[v] ?? 0 means "the current count, or 0 if there is none yet".

Sets: unique values

A Set holds values with no duplicates and no index. Adding an item that is already there does nothing.

void main() {
  var cities = <String>{'Ranchi', 'Patna'};
  cities.add('Ranchi');           // already there
  cities.add('Kolkata');
  print(cities);
  print(cities.contains('Patna'));

  var rolls = [3, 7, 3, 9, 7];
  print(rolls.toSet());           // remove duplicates
  print(rolls.toSet().length);
}
{Ranchi, Patna, Kolkata}
true
{3, 7, 9}
3

Careful: {} on its own makes an empty Map. Write <String>{} for an empty set.

Set maths

void main() {
  var cricket = {'Asha', 'Rohit', 'Meena'};
  var football = {'Rohit', 'Ravi'};
  print(cricket.union(football));
  print(cricket.intersection(football));
  print(cricket.difference(football));
}
{Asha, Rohit, Meena, Ravi}
{Rohit}
{Asha, Meena}

Maps of lists and lists of maps

Real data, such as the JSON an app gets from a server, is a mix of maps and lists:

void main() {
  var students = [
    {'name': 'Asha', 'marks': 88},
    {'name': 'Rohit', 'marks': 74},
  ];
  for (var s in students) {
    print('${s['name']} scored ${s['marks']}');
  }

  var classes = <String, List<String>>{
    '10A': ['Asha', 'Rohit'],
    '10B': ['Meena'],
  };
  classes['10B']!.add('Ravi');
  print(classes);
}
Asha scored 88
Rohit scored 74
{10A: [Asha, Rohit], 10B: [Meena, Ravi]}

When data gets bigger, turn each map into a class (see Classes and Objects) so the compiler can check field names for you.

List, Map or Set?

UseWhen
Listorder matters, duplicates allowed, access by position
Maplook up a value by a key: roll number to name, word to count
Setonly uniqueness matters: tags, visited pages, unique cities

Common mistakes

  • Writing var s = {}; and expecting a set; it is a map.
  • Using marks['Asha'] + 5: the lookup may be null; write (marks['Asha'] ?? 0) + 5.
  • Expecting a set to keep duplicates or to have set[0].
  • Changing a map while looping over it with for-in; collect the keys first or use removeWhere.
  • Mixing value types in one map without a class, so mistakes show up only at run time.

Key points

  • Map<K, V> stores unique keys with values; map[key] reads (or gives null), map[key] = v writes.
  • keys, values and entries let you loop over a map.
  • update, putIfAbsent, containsKey and remove are the everyday tools.
  • Set<T> keeps unique values; union, intersection and difference do set maths.
  • {} is an empty map; use <T>{} for an empty set.

Practice questions

1. Create a map of three states and their capitals, then print each pair on its own line.
void main() {
  var capitals = {'Jharkhand': 'Ranchi', 'Bihar': 'Patna', 'Odisha': 'Bhubaneswar'};
  capitals.forEach((state, city) => print('$state: $city'));
}
2. Count how many times each letter appears in 'banana'.
void main() {
  var count = <String, int>{};
  for (var ch in 'banana'.split('')) {
    count[ch] = (count[ch] ?? 0) + 1;
  }
  print(count);   // {b: 1, a: 3, n: 2}
}
3. What is the type of var x = {};?

Map<dynamic, dynamic>: empty braces make a map, not a set.

4. Find the students who play both games: {'Asha', 'Ravi', 'Meena'} and {'Ravi', 'Meena', 'Kiran'}.
void main() {
  var a = {'Asha', 'Ravi', 'Meena'};
  var b = {'Ravi', 'Meena', 'Kiran'};
  print(a.intersection(b));   // {Ravi, Meena}
}
5. Remove the duplicates from [5, 1, 5, 2, 1] and print the result as a list.
void main() {
  print([5, 1, 5, 2, 1].toSet().toList());   // [5, 1, 2]
}