What is the HashMap.values in Dart?

Overview

The values property can be used to get all values of the a HashMap object.

Note: Read more about the HashMap class here.

Syntax

Iterable<V> values

Return value

This property returns an iterable which contains all the values of the HashMap object.

The order of values in the iterable is the same as the order of keys that we get from the keys property. Iterating keys and values in parallel provides the matching pairs of keys and values.

Note: Modifying the map while iterating the values may result in an unhandled exception.Concurrent modification during iteration

Example

The code below demonstrates how to get all the values of a HashMap:

import 'dart:collection';
void main() {
//create a new hashmap which can have string type as key, and int type as value
HashMap map = new HashMap<String, int>();
// add two entries to the map
map["one"] = 1;
map["two"] = 2;
print('\nThe map is $map');
// use values property to get the values of the map
Iterable<int> values = map.values;
print('map.values: $values');
// using forEach and print the iterable
print('\nPrinting values Using forEach');
values.forEach((k) => print(k));
}

Explanation

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

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

  • Line 12: We use the values property to get all the values of map. We’ll get the values as an Iterable object. We print the returned Iterable object to get (1, 2).

  • Line 17: We used the forEach method of the values iterable and print all the elements (values) of the Iterable object.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources