CodeBlanks Logo Icon CodeBlanks

Summary - Sets and Maps

Combine Set and Map to write a phone book.

Summary - Sets and Maps

In this group you met two key collections. A Set holds unique elements; you manage it with add, contains and remove. A Map stores key-value pairs; you work with [], putIfAbsent and forEach.

Use a Set to prevent duplicates and a Map to bind a name to a value. Real tasks like phone books, code tables or tag lists combine the two.

In the final task you will merge them: a Set holds unique tags while a Map stores name-age pairs. You will see how the two collections work side by side.

Practice Tag Set

Create a Set<String> with three tags. Then print the Set with print.

Starter code

main.dart
void main() {
  // Define a Set with three tags

  // print
}

Sample solution

main.dart
void main() {
  Set<String> tags = {'yeni', 'onemli', 'acil'};
  print(tags);
}

Expected output

{yeni, onemli, acil}

Practice Phone book with a Set

Define a Set<String> with two tags. Then build a Map<String, String> with two people: name as key, phone as value. Print the Set first, then the Map.

Starter code

main.dart
void main() {
  // Define a Set and a Map

  // print Set first, then Map
}

Sample solution

main.dart
void main() {
  Set<String> tags = {'onemli', 'acil'};
  var phones = <String, String>{'Ayşe': '555-1000', 'Mert': '555-2000'};
  print(tags);
  print(phones);
}

Expected output

{onemli, acil}
{Ayşe: 555-1000, Mert: 555-2000}

Questions and answers

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

1 Set and Map

Term Meaning
Set Unique elements
Map Key-value pairs
add Element to a Set
putIfAbsent Map insert if absent

2 Which collection?

  • Map for duplicates
  • Set for duplicates Correct answer
  • Set for indexed access
  • Set for key-value

Explanation: a Set prevents duplicates automatically.

3 Map lookup

Question
void main() {
  var ages = <String, int>{'Ayşe': 28};
  print(ages____);
}
Answer
void main() {
  var ages = <String, int>{'Ayşe': 28};
  print(ages['Ayşe']);
}

Explanation: square brackets fetch the value for the key.

All lessons in Beginner