In Dart programming, Maps are dictionary-like data types that exist in key-value form (known as lock-key). There is no restriction on the type of data that goes in a map data type. Maps are very flexible and can mutate their size based on the requirements. However, it is important to note that all locks (keys) need to be unique inside a map data type.
A map is a collection of key/value pairs. The value is retrieved from a map with its associated key. Maps are also called dictionaries, associative arrays, or hash tables.
Depending on the iteration order, there are three types of maps in Dart:
- HashMap – unordered
- LinkedHashMap – ordered by insertion order
- SplayTreeMap – ordered by sorted keys
By default, creating an instance using Map constructor (Map
, Map.from
, or Map.of
) creates a LinkedHashMap
.
A map is created with a map literal or with a map constructor. To work with maps, we import the dart:collection
library.
Declaring a Dart Map
Dart Map can be defined in two methods.
- Using Map Literal
- Using Map Constructor
The syntax of declaring Dart Map is given below.
Map Literals:
Map can be declared using map literals as shown below:
Syntax: // Creating the Map using Map Literals var map_name = { key1 : value1, key2 : value2, ..., key n : value n }
Example:
void main() {
// Creating Map using is literals
var f = {'position1' : 'flutter', 'position2' : 'for', 'position3' : 'fever'};
// Printing Its content
print(f);
// Printing Specific Content
// Key is defined
print(f['position1']);
// Key is not defined
print(f[0]);
}
Map Constructors:
Syntax: // Creating the Map using Map Constructor var map_name = new Map(); // Assigning value and key inside Map map_name [ key ] = value;
Example :
Creating Map using Map Constructors
void main() {
// Creating Map using Constructors
var f = new Map();
// Inserting values into Map
f [0] = 'flutter';
f [1] = 'for';
f [2] = 'fever';
// Printing Its content
print(f);
// Printing Specific Content
// Key is defined
print(f[0]);
}
output:
{0: flutter, 1: for, 2: flutter} flutter
Map Properties in dart
Properties | Explanation |
---|---|
Keys | It is used to get all keys as an iterable object. |
values | It is used to get all values as an iterable object. |
Length | It returns the length of the Map object. |
isEmpty | If the Map object contains no value, it returns true. |
isNotEmpty | If the Map object contains at least one value, it returns true. |
Example:
void main() {
var student = new Map();
student['name'] = 'Tom';
student['age'] = 23;
student['course'] = 'B.tech';
student['Branch'] = 'Computer Science';
print(student);
// Get all Keys
print("The keys are : ${student.keys}");
// Get all values
print("The values are : ${student.values}");
// Length of Map
print("The length is : ${student.length}");
//isEmpty function
print(student.isEmpty);
//isNotEmpty function
print(student.isNotEmpty);
}
Output:
{name: Tom, age: 23, course: B.tech, Branch: Computer Science} The keys are : (name, age, course, Branch) The values are : (Tom, 23, B.tech, Computer Science) The length is : 4 false true
Map Methods in dart
The commonly used methods are given below.
addAll() – It adds multiple key-value pairs of other. The syntax is given below.
Syntax –
Map.addAll(Map<Key, Value> other)
Parameter:
- other – It denotes a key-value pair. It returns a void type.
Let’s understand the following example.
void main() {
Map student = {'name':'Tom','age': 23};
print('Map :${student}');
student.addAll({'dept':'Civil','email':'tom@xyz.com'});
print('Map after adding key-values :${student}');
}
Dart map removing pairs
We can remove pairs from the map with remove
, removeWhere
, or clear
.
main.dart
void main() { var words = { 1: 'sky', 2: 'fly', 3: 'ribbon', 4: 'falcon', 5: 'rock', 6: 'ocean', 7: 'cloud' }; words.remove(1); print(words); words.removeWhere((key, value) => value.startsWith('f')); print(words); words.clear(); print(words); }
The example removes pairs from the map of words.
words.remove(1);
With remove
, we delete the pair having key 1.
words.removeWhere((key, value) => value.startsWith('f'));
The removeWhere
deletes all pairs whose values (words) begin with letter f.
words.clear();
The clear
method removes all pairs from the map.
$ dart main.dart {2: fly, 3: ribbon, 4: falcon, 5: rock, 6: ocean, 7: cloud} {3: ribbon, 5: rock, 6: ocean, 7: cloud} {}
Dart Map fromIterables
The fromIterables
method creates a new map from the provided iterables.
main.dart
void main() { var letters = ['I', 'II', 'V', 'X', 'L']; var numbers = [1, 2, 5, 10, 50]; var data = Map<String, int>.fromIterables(letters, numbers); print(data); }
In the example, we create a map from two lists.
$ dart main.dart {I: 1, II: 2, V: 5, X: 10, L: 50}
Dart merge maps
We can merge maps with the addAll
method or the spread (…) operator.
main.dart
void main() { var f1 = {1: 'Apple', 2: 'Orange'}; var f2 = {3: 'Banana'}; var f3 = {4: 'Mango'}; var fruit = {}..addAll(f1)..addAll(f2)..addAll(f3); print(fruit); var fruit2 = Map.from(f1)..addAll(f2)..addAll(f3); print(fruit2); var fruit3 = {...f1, ...f2, ...f3}; print(fruit3); }
In the example, we have three maps. We merge them with addAll
and the spread operator.
$ dart main.dart {1: Apple, 2: Orange, 3: Banana, 4: Mango} {1: Apple, 2: Orange, 3: Banana, 4: Mango} {1: Apple, 2: Orange, 3: Banana, 4: Mango}
Dart containsKey/containsValue
With containsKey
and containsValue
, we can determine if a map contains a specific key and value.
main.dart
void main() { var myMap = {1: 'Apple', 2: 'Orange', 3: 'Banana'}; print(myMap.containsKey(1)); print(myMap.containsKey(3)); print(myMap.containsValue('Apple')); print(myMap.containsValue('Cherry')); }
The example uses the containsKey
and containsValue
methods for a small map.
$ dart main.dart true true true false
Dart map iteration
We can iterate over map pairs with forEach
method or for
statement.
main.dart
void main() { var fruit = {1: 'Apple', 2: 'Banana', 3: 'Cherry', 4: 'Orange'}; fruit.forEach((key, val) { print('{ key: $key, value: $val}'); }); print('---------------------------'); fruit.entries.forEach((e) { print('{ key: ${e.key}, value: ${e.value} }'); }); print('---------------------------'); for (var key in fruit.keys) print(key); for (var value in fruit.values) print(value); }
In the example, we loop over a map of fruit.
fruit.forEach((key, val) { print('{ key: $key, value: $val}'); });
With forEach
method, we print the key/value pairs of the fruit
map.
fruit.entries.forEach((e) { print('{ key: ${e.key}, value: ${e.value} }'); });
In a similar fashion, we loop over the entry objects of the fruit
map.
for (var key in fruit.keys) print(key); for (var value in fruit.values) print(value);
Finally, with for
statements, we go through the keys and values separately.
$ dart main.dart { key: 1, value: Apple} { key: 2, value: Banana} { key: 3, value: Cherry} { key: 4, value: Orange} --------------------------- { key: 1, value: Apple } { key: 2, value: Banana } { key: 3, value: Cherry } { key: 4, value: Orange } --------------------------- 1 2 3 4 Apple Banana Cherry Orange
Dart sort map
When we need to sort maps, we can use the SplayTreeMap
. The SplayTreeMap
is ordered by sorted keys.
main.dart
import 'dart:collection'; void main() { var fruit = new SplayTreeMap<int, String>(); fruit[0] = 'Banana'; fruit[5] = 'Plum'; fruit[6] = 'Strawberry'; fruit[2] = 'Orange'; fruit[3] = 'Mango'; fruit[4] = 'Blueberry'; fruit[1] = 'Apple'; print(fruit); fruit.forEach((key, val) { print('{ key: $key, value: $val}'); }); var sortedByValue = new SplayTreeMap<int, String>.from( fruit, (key1, key2) => fruit[key1].compareTo(fruit[key2])); print(sortedByValue); }
We have a map of fruit. By default, the pairs are ordered by the keys — numerically, in ascending order.
var sortedByValue = new SplayTreeMap<int, String>.from( fruit, (key1, key2) => fruit[key1].compareTo(fruit[key2]));
We create a sorted map by values from the original map. We pass the from
function a comparison function, which compares the values of the pairs.
$ dart main.dart {0: Banana, 1: Apple, 2: Orange, 3: Mango, 4: Blueberry, 5: Plum, 6: Strawberry} { key: 0, value: Banana} { key: 1, value: Apple} { key: 2, value: Orange} { key: 3, value: Mango} { key: 4, value: Blueberry} { key: 5, value: Plum} { key: 6, value: Strawberry} {1: Apple, 0: Banana, 4: Blueberry, 3: Mango, 2: Orange, 5: Plum, 6: Strawberry}
Map.map() method in Dart
The Map.map()
method can be used to create a new map with all entries modified or transformed.
Syntax
map_name.map((k, v))
map_name
is the name of the map.
Parameters
The map()
method requires a key-value pair of a specific map to transform to a new map.
Return type
Map.map()
returns a new key-value pair.
Code
The following code shows how to use the Map.map()
method in Dart:
void main() {
// Initialize map
Map map1 = {'one': 2, 'two': 6,'three': 9};
//Use .map() method
var transformedMap = map1.map((k, v) {
return MapEntry(k.toUpperCase(), v*v);
});
print(map1);
print('The transformed map: ${transformedMap}');
}
output:
{one: 2, two: 6, three: 9} The transformed map: {ONE: 4, TWO: 36, THREE: 81}
The code above changes keys and values of all entries of map1
based on the condition to create the transformedMap
. This changes the keys to uppercase and multiplies the values by themselves.
In this article, we have covered Dart maps.