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.
Parameter | Optional/Required | Description |
---|---|---|
convert | required | the function used to transform entries of the map |
Map.map() returns value of type Map<K2, V2>
.
In this example,
scores
with names as keys and scores as values.map()
method to transform each entry by dividing the score by 10.0, effectively converting scores to grades.grades
is printed, showing the grades corresponding to each name.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}
}
{Alice: 10.0, Bob: 8.0, Charlie: 9.0}
In this example,
map
with integers as keys and strings as values.map()
method to transform each entry by mapping keys to the lengths of their corresponding values.lengths
is printed, showing the lengths corresponding to each key.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}
}
{1: 3, 2: 3, 3: 5}
In this example,
words
with strings as keys and colors as values.map()
method to transform each entry by mapping keys to the lengths of their corresponding values.lengths
is printed, showing the lengths corresponding to each key.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}
}
{apple: 3, banana: 6, cherry: 3}
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.