Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator

How to get keys and entries of the LinkedHashMap in Dart

Programming Bytes

LinkedHashMap is an implementation of MapMap contains a list of key-value pairs as an element., 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 LinkedHashMap here.

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 value
  LinkedHashMap map = new LinkedHashMap<String, int>();
  
  // add two entries to the map
  map["one"] =  1;
  map["two"] =  2;
  print('\nThe map is $map');
  
  // use keys property to get the keys of the map
  Iterable<String> keys = map.keys;
  print('map.keys: $keys');

  // use entries property to get the entries of the map
  Iterable<MapEntry<String,int>> entries = map.entries;
  print('map.entries: $entries');
}
Get the key and entries of a LinkedHashMap

Explanation

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

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

  • Line 12: We use the keys property to get all the keys of the map. We will get the keys as an Iterable object. When we print the returned iterable, we will get (one, two).

  • Line 16: We use the entries property to get all the entries of the map. We will get the entries as an Iterable object.

RELATED TAGS

dart
communitycreator
RELATED COURSES

View all Courses

Keep Exploring