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.
Parameter | Optional/Required | Description |
---|---|---|
action | required | the function to apply to each key/value pair |
Map.forEach() returns value of type void
.
In this example,
map1
with string keys and integer values.forEach()
method to iterate over each key/value pair in map1
.void main() {
Map<String, int> map1 = {'one': 1, 'two': 2, 'three': 3};
map1.forEach((key, value) {
print('Key: $key, Value: $value');
});
}
Key: one, Value: 1 Key: two, Value: 2 Key: three, Value: 3
In this example,
map2
with integer keys and string values.forEach()
method to iterate over each key/value pair in map2
.void main() {
Map<int, String> map2 = {1: 'one', 2: 'two', 3: 'three'};
map2.forEach((key, value) {
print('Key: $key, Value: $value');
});
}
Key: 1, Value: one Key: 2, Value: two Key: 3, Value: three
In this example,
map3
with string keys and string values.forEach()
method to iterate over each key/value pair in map3
.void main() {
Map<String, String> map3 = {'apple': 'red', 'banana': 'yellow', 'cherry': 'red'};
map3.forEach((key, value) {
print('Key: $key, Value: $value');
});
}
Key: apple, Value: red Key: banana, Value: yellow Key: cherry, Value: red
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.