What is the LinkedHashMap.forEach() method in Dart?
Overview
In Dart, LinkedHashMap is a hash-table based implementation of
Note: Read more about
LinkedHashMaphere.
The forEach method executes a 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 valueLinkedHashMap map = new LinkedHashMap<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
-
Line 1: We import the
collectionlibrary. -
Line 4: We create a
LinkedHashMapobject with the namemap. -
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 aBiConsumer()function. Inside theBiConsumer()function, we:- Convert the key to uppercase and print it.
- Multiply the value by 2 and print it.