Home > Back-end >  DART : Merge two maps with identical key
DART : Merge two maps with identical key

Time:03-06

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]

Thank you for your help

CodePudding user response:

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]}
}
  •  Tags:  
  • dart
  • Related