Dart Map addAll()
Syntax & Examples
Syntax of Map.addAll()
The syntax of Map.addAll() method is:
void addAll(Map<K, V> other)
This addAll() method of Map adds all key/value pairs of other
to this map.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
other | required | the map whose key/value pairs will be added to this map |
Return Type
Map.addAll() returns value of type void
.
✐ Examples
1 Merge maps with string keys and integer values
In this example,
- We create two maps,
map1
andmap2
, with key/value pairs. - We then use the
addAll()
method onmap1
, passingmap2
as the argument, to add all key/value pairs frommap2
tomap1
. - We print the updated
map1
to standard output.
Dart Program
void main() {
Map<String, int> map1 = {'apple': 1, 'banana': 2};
Map<String, int> map2 = {'cherry': 3};
map1.addAll(map2);
print('Updated map1: $map1');
}
Output
Updated map1: {apple: 1, banana: 2, cherry: 3}
2 Merge maps with integer keys and string values
In this example,
- We create two maps,
map1
andmap2
, with key/value pairs. - We then use the
addAll()
method onmap1
, passingmap2
as the argument, to add all key/value pairs frommap2
tomap1
. - We print the updated
map1
to standard output.
Dart Program
void main() {
Map<int, String> map1 = {1: 'one', 2: 'two'};
Map<int, String> map2 = {3: 'three'};
map1.addAll(map2);
print('Updated map1: $map1');
}
Output
Updated map1: {1: one, 2: two, 3: three}
3 Merge maps with string keys and string values
In this example,
- We create two maps,
map1
andmap2
, with key/value pairs. - We then use the
addAll()
method onmap1
, passingmap2
as the argument, to add all key/value pairs frommap2
tomap1
. - We print the updated
map1
to standard output.
Dart Program
void main() {
Map<String, String> map1 = {'name': 'John'};
Map<String, String> map2 = {'age': '30'};
map1.addAll(map2);
print('Updated map1: $map1');
}
Output
Updated map1: {name: John, age: 30}
Summary
In this Dart tutorial, we learned about addAll() method of Map: the syntax and few working examples with output and detailed explanation for each example.