Maps in Dart

Maps in Dart#

About#

A Map in Dart is a collection of key-value pairs where each key is unique, and each key maps to exactly one value. Maps are often used to store related data, such as a dictionary where words (keys) map to their definitions (values). Keys must be unique, but values can be duplicated.

How Maps Work#

  • Keys: Unique identifiers for values.
  • Values: Data associated with the keys.
  • You access values by their keys instead of by an index (as in Lists).
  • Maps are unordered by default, meaning the insertion order of keys is not maintained.

Types of Maps:#

  1. HashMap: The default map implementation, which does not preserve order.
  2. LinkedHashMap: Maintains the order in which keys are inserted.
  3. SplayTreeMap: Automatically sorts keys based on their natural order or a custom comparison.

Usage#

Maps are useful when:

  • You need to associate values with unique keys.
  • You need fast lookups, additions, and removals of key-value pairs.
  • The order of elements is not a priority (unless using LinkedHashMap).

Common Operations:#

  • Add or update key-value pairs: map[key] = value
  • Access value by key: map[key]
  • Remove key-value pairs: map.remove(key)
  • Check if a key exists: map.containsKey(key)
  • Map length: map.length

Example#

Example 1: Creating and Using a Map#

void main() {
  // Creating a map
  Map<String, int> ageMap = {'Alice': 25, 'Bob': 30};
  
  // Accessing a value by key
  print(ageMap['Alice']); // Output: 25
  
  // Adding a new key-value pair
  ageMap['Charlie'] = 35;
  
  // Modifying an existing value
  ageMap['Alice'] = 26;
  
  // Removing a key-value pair
  ageMap.remove('Bob');
  
  // Checking if a key exists
  print(ageMap.containsKey('Charlie')); // Output: true
  
  // Printing the map
  print(ageMap); // Output: {Alice: 26, Charlie: 35}
}
```dart
### Example 2: Using Map Constructor

```void main() {
  // Creating a map using the Map constructor
  Map<int, String> numMap = Map();
  
  // Adding key-value pairs
  numMap[1] = 'One';
  numMap[2] = 'Two';
  
  // Accessing and printing values
  print(numMap[1]); // Output: One
  print(numMap);    // Output: {1: One, 2: Two}
}

Conclusion#

A Map in Dart is a versatile collection when you need to associate unique keys with values. It is highly efficient for lookups, and it allows you to store data that requires key-based access. Maps are commonly used for tasks such as representing dictionaries or tables of data.