The forEach
method will iterate over each entry of the HashMap and execute the passed
Note: Here’s a hash-table based implementation of
. Read more about HashMap here. Map Map contains a list of key-value pairs as an element.
The function has the following syntax:
void forEach(void action(K key,V value ))
This method takes the function which needs to be executed on each entry of the map as an argument. The consumer function will have two arguments: the key
and value
of the current entry.
This method does not return any value.
The code below demonstrates how to use the forEach
method:
import 'dart:collection';void main() {//create a new hashmap which can have string type as key,//and int type as valueHashMap map = new HashMap<String, int>();// add two entries to the mapmap["one"] = 1;map["two"] = 2;map["three"] = 3;print('The map is $map');// use forEach to loop each entry of the mapprint("\nUsing 'forEach' method to print all entries of map");map.forEach((key, value){print('${key.toUpperCase()} - ${value * 2}');});}
In the above code, we do the following:
In line 1, we import the collection
library.
In line 4, we create a HashMap
object with the name map
.
In lines 7-9, we add three new entries to the map
. Now, the map is {three: 3, one: 1, two: 2}
.
In line 16, we use the forEach
method with a BiConsumer function. Inside the BiConsumer function:
2
and print it.