How to get keys and entries of the LinkedHashMap in Dart
LinkedHashMap is an implementation of
, which is based on a hash table. The LinkedHashMap maintains the insertion order of the entries. we can read more about the concept of a Map Map contains a list of key-value pairs as an element. LinkedHashMaphere.
Getting keys
The keys property can be used to get all the keys of the LinkedHashMap in the insertion order.
Syntax
Iterable<K> keys
Return value
This property returns an iterable that contains all the keys of the LinkedHashMap. The iterable contains the keys in the insertion order.
Getting entries
The entries property can be used to get all the entries (key-value pairs) of the LinkedHashMap.
Syntax
Iterable<MapEntry<K, V>> get entries;
Return value
This property returns an iterable that contains all the key-value pairs of the LinkedHashMap in the insertion order.
Note: Modifying the map while iterating the keys may result in an unhandled exception.
Code
The code below demonstrates how we can get all the keys and entries of a map:
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;print('\nThe map is $map');// use keys property to get the keys of the mapIterable<String> keys = map.keys;print('map.keys: $keys');// use entries property to get the entries of the mapIterable<MapEntry<String,int>> entries = map.entries;print('map.entries: $entries');}
Explanation
-
Line 4: We create a new
LinkedHashMapobject with the namemap. -
Lines 7–8: We add two new entries to the
map. Now, the map is{one: 1, two: 2}. -
Line 12: We use the
keysproperty to get all the keys of themap. We will get the keys as anIterableobject. When we print the returned iterable, we will get(one, two). -
Line 16: We use the
entriesproperty to get all the entries of themap. We will get the entries as anIterableobject.