Dart Map forEach()
Syntax & Examples
Syntax of Map.forEach()
The syntax of Map.forEach() method is:
void forEach(void action(K key, V value))
This forEach() method of Map applies action
to each key/value pair of the map.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
action | required | the function to apply to each key/value pair |
Return Type
Map.forEach() returns value of type void
.
✐ Examples
1 Iterate over a map of strings and integers
In this example,
- We create a map named
map1
with string keys and integer values. - We use the
forEach()
method to iterate over each key/value pair inmap1
. - For each pair, we print the key and value to standard output.
Dart Program
void main() {
Map<String, int> map1 = {'one': 1, 'two': 2, 'three': 3};
map1.forEach((key, value) {
print('Key: $key, Value: $value');
});
}
Output
Key: one, Value: 1 Key: two, Value: 2 Key: three, Value: 3
2 Iterate over a map of integers and strings
In this example,
- We create a map named
map2
with integer keys and string values. - We use the
forEach()
method to iterate over each key/value pair inmap2
. - For each pair, we print the key and value to standard output.
Dart Program
void main() {
Map<int, String> map2 = {1: 'one', 2: 'two', 3: 'three'};
map2.forEach((key, value) {
print('Key: $key, Value: $value');
});
}
Output
Key: 1, Value: one Key: 2, Value: two Key: 3, Value: three
3 Iterate over a map of strings
In this example,
- We create a map named
map3
with string keys and string values. - We use the
forEach()
method to iterate over each key/value pair inmap3
. - For each pair, we print the key and value to standard output.
Dart Program
void main() {
Map<String, String> map3 = {'apple': 'red', 'banana': 'yellow', 'cherry': 'red'};
map3.forEach((key, value) {
print('Key: $key, Value: $value');
});
}
Output
Key: apple, Value: red Key: banana, Value: yellow Key: cherry, Value: red
Summary
In this Dart tutorial, we learned about forEach() method of Map: the syntax and few working examples with output and detailed explanation for each example.