What is the HashMap.forEach() method in Dart?

The forEach method will iterate over each entry of the HashMap and execute the passed BiConsumer functionIt represents a function that accepts a two-input argument and returns no result.. The key and value of the entry are passed as an argument to the BiConsumer function.

Note: Here’s a hash-table based implementation of MapMap contains a list of key-value pairs as an element.. Read more about HashMap here.

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 value
HashMap map = new HashMap<String, int>();
// add two entries to the map
map["one"] = 1;
map["two"] = 2;
map["three"] = 3;
print('The map is $map');
// use forEach to loop each entry of the map
print("\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 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:

    • We convert the key to uppercase and print it.
    • We multiply the value by 2 and print it.