Dart Set map()
Syntax & Examples
Set.map() method
The `map` method in Dart returns a new lazy Iterable with elements that are created by calling the provided function on each element of the set in iteration order.
Syntax of Set.map()
The syntax of Set.map() method is:
Iterable<T> map<T>(T f(E e))
This map() method of Set returns a new lazy Iterable with elements that are created by calling f on each element of this Iterable in iteration order.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
f | required | The function to apply to each element of the set. |
Return Type
Set.map() returns value of type Iterable<T>
.
✐ Examples
1 Map integers to strings
In this example,
- We create a Set
set
containing integers. - We use the
map()
method with a function that converts each integer to a string with a prefix 'Number'. - We print the mapped Iterable to standard output.
Dart Program
void main() {
Set<int> set = {1, 2, 3};
Iterable<String> mappedSet = set.map((e) => 'Number $e');
print(mappedSet);
}
Output
(Number 1, Number 2, Number 3)
2 Map strings to their lengths
In this example,
- We create a Set
set
containing strings. - We use the
map()
method with a function that computes the length of each string. - We print the mapped Iterable to standard output.
Dart Program
void main() {
Set<String> set = {'apple', 'banana', 'orange'};
Iterable<int> mappedSet = set.map((e) => e.length);
print(mappedSet);
}
Output
(5, 6, 6)
Summary
In this Dart tutorial, we learned about map() method of Set: the syntax and few working examples with output and detailed explanation for each example.