Map Entries in Dart

Map Entries in Dart

Working with Key-Value Pairs in Maps

How It Works

In Dart, a Map is a collection of key-value pairs where each key is unique and maps to a specific value. The Map class provides methods to work with these pairs, including accessing, modifying, and iterating over the entries. Each entry in a map is represented by a MapEntry object, which contains a key and its associated value.

  • Key-Value Pairs: Each element in a map is a pair consisting of a key and a value.
  • MapEntry: Represents a single key-value pair in a map.

How to Use

To work with map entries, you can use the entries property of a Map which returns an iterable of MapEntry objects. This allows you to iterate over and manipulate the key-value pairs directly.

Example: Working with Map Entries

Accessing and Iterating Over Map Entries

void main() {
  Map<String, int> scores = {
    'Alice': 90,
    'Bob': 85,
    'Charlie': 92
  };
  
  // Accessing map entries
  for (MapEntry<String, int> entry in scores.entries) {
    print('${entry.key}: ${entry.value}');
  }
  // Output:
  // Alice: 90
  // Bob: 85
  // Charlie: 92
}
  • In this example, we iterate over the entries of the scores map and print each key-value pair.

Modifying Map Entries

void main() {
  Map<String, int> scores = {
    'Alice': 90,
    'Bob': 85,
    'Charlie': 92
  };
  
  // Modifying a map entry
  scores.update('Bob', (value) => value + 10);
  
  print(scores); // Output: {Alice: 90, Bob: 95, Charlie: 92}
}
  • Here, we use the update method to modify the value associated with the key ‘Bob’.

Adding New Map Entries

void main() {
  Map<String, int> scores = {
    'Alice': 90,
    'Bob': 85
  };
  
  // Adding a new map entry
  scores['Charlie'] = 92;
  
  print(scores); // Output: {Alice: 90, Bob: 85, Charlie: 92}
}
  • In this example, a new entry is added to the scores map by assigning a value to a new key.

Removing Map Entries

void main() {
  Map<String, int> scores = {
    'Alice': 90,
    'Bob': 85,
    'Charlie': 92
  };
  
  // Removing a map entry
  scores.remove('Bob');
  
  print(scores); // Output: {Alice: 90, Charlie: 92}
}
  • We use the remove method to delete the entry with the key ‘Bob’ from the scores map.

Conclusion

Working with map entries in Dart allows you to effectively manage key-value pairs in collections. You can access, modify, add, and remove entries, providing flexibility in how you handle data in maps. Using methods like entries, update, and remove, you can perform various operations on map entries efficiently.