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
HashMapclass 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 valueHashMap map = new HashMap<String, int>();// add two entries to the mapmap["one"] = 1;map["two"] = 2;print('\nThe map is $map');// use values property to get the values of the mapIterable<int> values = map.values;print('map.values: $values');// using forEach and print the iterableprint('\nPrinting values Using forEach');values.forEach((k) => print(k));}
Explanation
-
Line 4: We create a new
HashMapobject with the namemap. -
Lines 7–8: We add two new entries to
map. Now,mapis{one: 1, two: 2}. -
Line 12: We use the
valuesproperty to get all the values ofmap. We’ll get the values as anIterableobject. We print the returnedIterableobject to get(1, 2). -
Line 17: We used the
forEachmethod of thevaluesiterable and print all the elements (values) of theIterableobject.