Dart Map addEntries()
Syntax & Examples
Syntax of Map.addEntries()
The syntax of Map.addEntries() method is:
void addEntries(Iterable<MapEntry<K, V>> newEntries) This addEntries() method of Map adds all key/value pairs of newEntries to this map.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
newEntries | required | an iterable of key/value pairs to add to the map |
Return Type
Map.addEntries() returns value of type void.
✐ Examples
1 Add multiple entries to a map
In this example,
- We create a map
mapwith initial key/value pairs. - We create an iterable
newEntriescontaining additional key/value pairs. - We then use the
addEntries()method to add all key/value pairs fromnewEntriestomap. - We print
mapafter adding the entries to standard output.
Dart Program
void main() {
var map = {'a': 1, 'b': 2};
var newEntries = {'c': 3, 'd': 4}.entries;
map.addEntries(newEntries);
print(map);
}Output
{a: 1, b: 2, c: 3, d: 4}2 Add a single entry to a map
In this example,
- We create a map
mapwith initial key/value pairs. - We create an iterable
newEntriescontaining a single key/value pair. - We then use the
addEntries()method to add the key/value pair fromnewEntriestomap. - We print
mapafter adding the entry to standard output.
Dart Program
void main() {
var map = {'x': 'apple', 'y': 'banana'};
var newEntries = {'z': 'cherry'}.entries;
map.addEntries(newEntries);
print(map);
}Output
{x: apple, y: banana, z: cherry}3 Add a new ID to a map of names
In this example,
- We create a map
mapwith initial key/value pairs representing IDs and names. - We create an iterable
newEntriescontaining a single key/value pair representing a new ID and name. - We then use the
addEntries()method to add the new ID and name tomap. - We print
mapafter adding the entry to standard output.
Dart Program
void main() {
var map = {'id1': 'John', 'id2': 'Doe'};
var newEntries = {'id3': 'Jane'}.entries;
map.addEntries(newEntries);
print(map);
}Output
{id1: John, id2: Doe, id3: Jane}Summary
In this Dart tutorial, we learned about addEntries() method of Map: the syntax and few working examples with output and detailed explanation for each example.