How to iterate a HashMap in Dart in different ways

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));
}

Output: Dart iterate keys of hashmap

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: