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

Overview

In Dart, LinkedHashMap is a hash-table based implementation of MapMap contains a list of key-value pairs as an element.. It maintains the insertion order of the entries.

Note: Read more about LinkedHashMap here.

The forEach method executes a BiConsumer functionIt represents a function that accepts a two-input argument and returns no result. for all the entries of the LinkedHashMap.

Syntax

void forEach(void action(K key,V value ))

Parameter value

This method takes a function that needs to be executed on each entry of the LinkedHashMap as an argument. The consumer function has two arguments key, and the value of the current entry. The map is iterated based on the insertion order.

Return value

This method doesn’t return any value.

Code

The below code demonstrates the use of the forEach() method.

import 'dart:collection';
void main() {
//create a new LinkedHashMap which can have string type as key, and int type as value
LinkedHashMap map = new LinkedHashMap<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

  • Line 1: We import the collection library.

  • Line 4: We create a LinkedHashMap object with the name map.

  • Lines 7–9: We add three new entries to the map. Now, the map is {three: 3, one: 1, two: 2}

  • Line 16: We use the forEach() method with a BiConsumer() function. Inside the BiConsumer() function, we:

    • Convert the key to uppercase and print it.
    • Multiply the value by 2 and print it.