How to iterate a HashMap in Dart:
This post will show you how to iterate over a HashMap in Dart with examples. We can use the forEach method to iterate over a HashMap. Let’s understand how forEach works.
Definition and example of forEach:
The forEach method is defined as:
forEach(void f(K k, V v)) → void
We can pass one function to the forEach method. It will use that function with each pairs of the HashMap.
import 'dart:collection';
void main() {
final Map<int, String> hashMap =
HashMap.from({1: "one", 2: "two", 3: "three", 4: "four", 5: "five"});
print("Following are the contents of the HashMap: ");
hashMap.forEach((k, v) => print('{${k}, ${v}}'));
}
It will print:
Following are the contents of the HashMap:
{1, one}
{2, two}
{3, three}
{4, four}
{5, five}
How to use forEach to iterate over the keys of a HashMap:
We can get the keys of a HashMap with the keys property. This returns an iterable:
Iterable<K> get keys
We can use a forEach loop to iterate over these keys:
import 'dart:collection';
void main() {
final Map<int, String> hashMap =
HashMap.from({1: "one", 2: "two", 3: "three", 4: "four", 5: "five"});
print("Following are the keys of the HashMap: ");
final keys = hashMap.keys;
keys.forEach((k) => print(k));
}
How to use forEach to iterate over the values of a HashMap:
Similar to the above example, we can also read the values of a HashMap to get all values. It returns one Iterable:
Iterable<V> get values;
As this is an Iterable, we can use a forEach loop to iterate over the values:
import 'dart:collection';
void main() {
final Map<int, String> hashMap =
HashMap.from({1: "one", 2: "two", 3: "three", 4: "four", 5: "five"});
print("Following are the values of the HashMap: ");
final values = hashMap.values;
values.forEach((v) => print(v));
}
It will print the values:
Following are the values of the HashMap:
one
two
three
four
five
If we have to check anything in the values or keys of a HashMap, we can iterate over its values or keys instead of iterating over its key-value pairs.
Reference:
You might also like:
- How to create a string from ASCII values in Dart
- Dart StringBuffer class explanation with examples
- 5 ways in Dart to print the multiplication table
- Introduction to Queue in Dart and its methods
- How to add and remove items from a Queue in Dart
- How to remove and retain items from Queue in Dart with condition
- Dart Queue reduce function example
- Dart HashMap explanation with examples
- How to add and remove items of a HashMap in Dart