What is the HashMap.forEach() method in Dart?
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.
Syntax
The function has the following syntax:
void forEach(void action(K key,V value ))
Parameter
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.
Return value
This method does not return any value.
Code
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}');});}
Explanation
In the above code, we do the following:
-
In line 1, we import the
collectionlibrary. -
In line 4, we create a
HashMapobject with the namemap. -
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
forEachmethod with a BiConsumer function. Inside the BiConsumer function:- We convert the key to uppercase and print it.
- We multiply the value by
2and print it.