Combine/merge multiple maps into 1 map

2020-06-30 04:48发布

问题:

How can I combine/merge 2 or more maps in dart into 1 map? for example I have something like:

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

I want:

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

回答1:

you can use addAll method of Map object

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

var thirdMap = {};

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

print(thirdMap);

Or

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

Update

Since dart sdk 2.3 You can use spread operator ...

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

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


回答2:

Another option is using CombinedMapView from package:collection:

new CombinedMapView([firstMap, secondMap])

It doesn't create a merged map, but creates a Map that is a view of both.



回答3:

alternate syntax using Map.addAll, Iterable.reduce and cascading operator, for combining a lot of maps:

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

live dartpad example https://dartpad.dartlang.org/9cd116d07d2f45a9b890b4b1186dcc5e



标签: dart