In Dart, LinkedHashMap
is a hash-table based implementation of
Note: Read more about
LinkedHashMap
here.
The forEach
method executes a LinkedHashMap
.
void forEach(void action(K key,V 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.
This method doesn’t return any value.
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}');});}
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: