【问题标题】:DART : Merge two maps with identical keyDART:合并两个具有相同键的地图
【发布时间】:2022-06-19 17:35:08
【问题描述】:

假设我有这些地图:

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

我想合并它们而不用相同的键覆盖值以获得此输出:

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

我同时使用了 spread 运算符和 adAll 方法,并且都将键 1 的值覆盖为 {1: [d], 2: [c]} 而不是 {1: [a, b, d], 2: [c]

【问题讨论】:

    标签: dart


    【解决方案1】:
    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]}
    }
    

    【讨论】:

    • 工作完美,非常感谢您
    猜你喜欢
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    相关资源
    最近更新 更多