将多个地图合并/合并为1个地图

smr*_*iti 14 dart

如何将dart中的2个或更多地图合并/合并到1个地图中?例如,我有类似的东西:

 var firstMap = {"1":"2"};
 var secondMap = {"1":"2"};
 var thirdMap = {"1":"2"};
Run Code Online (Sandbox Code Playgroud)

我想要:

 var finalMap = {"1":"2", "1":"2", "1":"2"};
Run Code Online (Sandbox Code Playgroud)

Had*_*ard 34

你可以使用对象的addAll方法Map

var firstMap = {"1":"2"};
var secondMap = {"2":"3"};

var thirdMap = {};

thirdMap.addAll(firstMap);
thirdMap.addAll(secondMap);

print(thirdMap);
Run Code Online (Sandbox Code Playgroud)

要么

var thirdMap = {}..addAll(firstMap)..addAll(secondMap);
Run Code Online (Sandbox Code Playgroud)

  • var finalMap = {} .. addAll(firstMap).. addAll(secondMap).. addAll(thirdMap); (3认同)

MrH*_*DEn 11

 var firstMap = {"1":"5"};
 var secondMap = {"1":"6"};
 var thirdMap = {"2":"7"};
 
 var finalMap = {...firstMap, ...secondMap, ...thirdMap};
 // finalMap: {"1":"6", "2":"7"};
Run Code Online (Sandbox Code Playgroud)

"1"请注意,具有值的键"5"将被覆盖"6"


小智 9

使用Map.addAll,Iterable.reduce级联运算符的替代语法,用于组合大量地图:

var combinedMap = mapList.reduce( (map1, map2) => map1..addAll(map2) );
Run Code Online (Sandbox Code Playgroud)

实时飞镖示例 https://dartpad.dartlang.org/9cd116d07d2f45a9b890b4b1186dcc5e


小智 6

我为可迭代的地图提出了一个“单行”解决方案:

var finalMap = Map.fromEntries(mapList.expand((map) => map.entries));
Run Code Online (Sandbox Code Playgroud)


mat*_*rey 5

另一种选择是使用CombinedMapViewfrom package:collection

new CombinedMapView([firstMap, secondMap])
Run Code Online (Sandbox Code Playgroud)

它不会创建合并的地图,而是会创建一个同时包含两者Map视图