DART : Merge two maps with identical key

Viewed 402

Suppose I have these maps:

Map<int,List<String>>  firstMap   = {1:["a", "b"]};
Map<int,List<String>>  secondMap  = {2:["c"]};
Map<int,List<String>>  thirdMap   = {1:["d"]};

I want to merge them without overwriting values with same key to have this output:

{1: [a, b, d], 2: [c]

I used both spread operator and adAll method and both overwrite the value for key 1 to have {1: [d], 2: [c]} instead of {1: [a, b, d], 2: [c].

1 Answers
void main() {
  Map<int, List<String>> firstMap = {1: ["a", "b"]};
  Map<int, List<String>> secondMap = {2: ["c"]};
  Map<int, List<String>> thirdMap = {1: ["d"]};

  var mergedMap = <int, List<String>>{};
  for (var map in [firstMap, secondMap, thirdMap]) {
    for (var entry in map.entries) {
      // Add an empty `List` to `mergedMap` if the key doesn't already exist
      // and then merge the `List`s.
      (mergedMap[entry.key] ??= []).addAll(entry.value);
    }
  }
  print(mergedMap); // Prints: {1: [a, b, d], 2: [c]}
}
Related