Dart Map map()
Syntax & Examples
Syntax of Map.map()
The syntax of Map.map() method is:
Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> convert(K key, V value))
This map() method of Map returns a new map where all entries of this map are transformed by the given convert
function.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
convert | required | the function used to transform entries of the map |
Return Type
Map.map() returns value of type Map<K2, V2>
.
✐ Examples
1 Convert scores to grades
In this example,
- We create a map
scores
with names as keys and scores as values. - We then use the
map()
method to transform each entry by dividing the score by 10.0, effectively converting scores to grades. - The transformed map
grades
is printed, showing the grades corresponding to each name.
Dart Program
void main() {
Map<String, int> scores = {'Alice': 100, 'Bob': 80, 'Charlie': 90};
Map<String, double> grades = scores.map((key, value) => MapEntry(key, value / 10.0));
print(grades); // Output: {Alice: 10.0, Bob: 8.0, Charlie: 9.0}
}
Output
{Alice: 10.0, Bob: 8.0, Charlie: 9.0}
2 Map keys to their lengths
In this example,
- We create a map
map
with integers as keys and strings as values. - We then use the
map()
method to transform each entry by mapping keys to the lengths of their corresponding values. - The transformed map
lengths
is printed, showing the lengths corresponding to each key.
Dart Program
void main() {
Map<int, String> map = {1: 'One', 2: 'Two', 3: 'Three'};
Map<int, int> lengths = map.map((key, value) => MapEntry(key, value.length));
print(lengths); // Output: {1: 3, 2: 3, 3: 5}
}
Output
{1: 3, 2: 3, 3: 5}
3 Map strings to their lengths
In this example,
- We create a map
words
with strings as keys and colors as values. - We then use the
map()
method to transform each entry by mapping keys to the lengths of their corresponding values. - The transformed map
lengths
is printed, showing the lengths corresponding to each key.
Dart Program
void main() {
Map<String, String> words = {'apple': 'red', 'banana': 'yellow', 'cherry': 'red'};
Map<String, int> lengths = words.map((key, value) => MapEntry(key, value.length));
print(lengths); // Output: {apple: 3, banana: 6, cherry: 3}
}
Output
{apple: 3, banana: 6, cherry: 3}
Summary
In this Dart tutorial, we learned about map() method of Map: the syntax and few working examples with output and detailed explanation for each example.