Map
- Dart course
- Intermediate
- Lesson 43/116
- 5 min
Learn key-value collections with Map<K,V>.
Map<K,V>
Map<K,V> stores key-value pairs. Each key is unique; one key maps to one value. K is the key type and V is the value type.
Create a Map with var scores = <String, int>{'Alex': 90, 'Mia': 85};. Keys are String, values are int. To add a new pair write scores['Bob'] = 78;.
Access a value with scores['Alex']. The length gives the pair count. A Map is ideal for name-age, product-price and similar mappings.
Map operations
To add a pair write map['key'] = value. If the key exists the value is updated. Access a value again with map['key'].
Example: var s = <String, int>{'Alex': 90}; s['Bob'] = 78; print(s);. Output: {Alex: 90, Bob: 78}. s.length gives 2.
A Map provides fast lookup. A value is reached by key in average O(1) time. This is far more efficient than lists for large data sets.
Practice Create a score table
Create a score table with <String, int>{'Alex': 90, 'Mia': 85}. Add a new pair with scores['Bob'] = 78. Print the Map first, then the length.
Starter code
void main() {
// create a Map with String keys and int values
// add a new key, print the Map and its length
}Sample solution
void main() {
var scores = <String, int>{'Alex': 90, 'Mia': 85};
scores['Bob'] = 78;
print(scores);
print(scores.length);
}Expected output
{Alex: 90, Mia: 85, Bob: 78}
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Map parts
| Term | Meaning |
|---|---|
<String, int> |
Key and value type |
{'Alex': 90} |
Key-value pair |
scores['Bob'] = 78 |
Add a new pair |
length |
Pair count |
2 What happens if you assign two values to the same Map key?
var m = <String, int>{};
m['a'] = 1;
m['a'] = 2;- Two 'a' keys appear
- It throws an error
- The second value overwrites the first Correct answer
- The values are summed
Explanation: assigning to the same key overwrites the previous value.
3 Add a pair to the Map
var scores = <String, int>{'Alex': 90};
____['Bob'] = 78;
var scores = <String, int>{'Alex': 90};
scores['Bob'] = 78;
Explanation: scores['Bob'] = 78 adds a new pair.