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

时间:2017-07-19 20:37:29

标签: dart

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

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

我想:

 var finalMap = {"1":"2", "1":"2", "1":"2"};

4 个答案:

答案 0 :(得分:16)

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

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

var thirdMap = {};

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

print(thirdMap);

或者

var thirdMap = {}..addAll(firstMap)..addAll(secondMap);

更新

自dart sdk 2.3 您可以使用展开运算符...

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

final thirdMap = {
   ...firstMap,
   ...secondMap,
};

答案 1 :(得分:5)

另一种选择是使用package:collection中的CombinedMapView

new CombinedMapView([firstMap, secondMap])

它不会创建合并的地图,但会创建一个Map,它是两者的视图

答案 2 :(得分:2)

使用Map.addAllIterable.reducecascading operator的替代语法,用于组合大量地图:

var combinedMap = mapList.reduce( (map1, map2) => map1..addAll(map2) );

live dartpad示例 https://dartpad.dartlang.org/9cd116d07d2f45a9b890b4b1186dcc5e

答案 3 :(得分:1)

我为Maps Iterable提出了“单行”解决方案:

var finalMap = Map.fromEntries(mapList.expand((map) => map.entries));