Map Interface
In Dart, Maps are unordered key-value pair collection that sets an associate key to the values within. To define a Map, specify the key type and the value type inside the angle brackets(<>) as shown below:
Syntax:
Map<int, string> fruits = {1: "Mango", 2:"Apple", 3:"Banana"}
Example:
The map collection stores the objects as a key-value pair. An example is shown below.
void main() {
// Initializing the map with sample values.
var geekMap = {1:"Apple",2:"Mango",3:"Banana"};
print(geekMap);
// Adding elements by different methods.
geekMap.addAll({4:'Pineapple',2:'Grapes'});
geekMap[9]="Kiwi";
print(geekMap);
// printing key and values
print('Keys: ${geekMap.keys} \nValues: ${geekMap.values}');
// removing an element from the map by its key
geekMap.remove(2);
// printing the map and its length
print('{$geekMap} length is ${geekMap.length}');
}
Output:
{1: Apple, 2: Mango, 3: Banana}
{1: Apple, 2: Grapes, 3: Banana, 4: Pineapple, 9: Kiwi}
Keys: (1, 2, 3, 4, 9)
Values: (Apple, Grapes, Banana, Pineapple, Kiwi)
{{1: Apple, 3: Banana, 4: Pineapple, 9: Kiwi}} length is 4
Classes Associated with Map Interfaces
Classes | Description |
---|---|
MapBase<K, V> | This is the base class for Map. |
HashMap<K, V> | Map based on hash table i.e unordered map. |
LinkedHashMap<K, V> | Similar to HashMap but based on LinkedList. |
SplayTreeMap<K, V> | The map ensures that its keys are ordered, and just like |
UnmodifiableMapBase<K, V> | Basic implementation of an unmodifiable Map. |
UnmodifiableMapView<K, V> | Unmodifiable view of the map. |
i. Hashmap
In the Dart programming language, a HashMap is a collection that stores key-value pairs, where the keys are unique and the values can be of any type. Here is an example of how to use a HashMap in Dart:
import 'dart:collection';
void main() {
// Create a new HashMap
var map = HashMap<int, String>();
// Add some key-value pairs to the map
map[1] = 'one';
map[2] = 'two';
map[3] = 'three';
// Access the value for a specific key
print(map[1]); // Output: one
// Iterate over the map
map.forEach((key, value) {
print('$key: $value');
});
}
Output:
one
two
three
Dart – Collections
Collections are groups of objects that represent a particular element. The dart::collection library is used to implement the Collection in Dart. There are a variety of collections available in Dart.
Contact Us