Dart Set expand()
Syntax & Examples
Set.expand() method
The `expand` method in Dart expands each element of the set into zero or more elements.
Syntax of Set.expand()
The syntax of Set.expand() method is:
Iterable<T> expand<T>(Iterable<T> f(E element))
This expand() method of Set expands each element of this Iterable into zero or more elements.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
f | required | A function that takes an element of the set as input and returns an iterable of elements to expand into. |
Return Type
Set.expand() returns value of type Iterable<T>
.
✐ Examples
1 Expand strings into individual characters
In this example,
- We create a Set
set
containing strings. - We use the
expand()
method with a function that splits each string into individual characters. - We print the expanded set to standard output.
Dart Program
void main() {
Set<String> set = {'apple', 'banana', 'orange'};
Iterable<String> expandedSet = set.expand((element) => element.split(''));
print('Expanded set: $expandedSet');
}
Output
Expanded set: (a, p, p, l, e, b, a, n, a, n, a, o, r, a, n, g, e)
2 Expand integers into consecutive pairs
In this example,
- We create a Set
set
containing integers. - We use the
expand()
method with a function that creates consecutive pairs from each integer. - We print the expanded set to standard output.
Dart Program
void main() {
Set<int> set = {1, 2, 3};
Iterable<int> expandedSet = set.expand((element) => [element, element + 1]);
print('Expanded set: $expandedSet');
}
Output
Expanded set: (1, 2, 2, 3, 3, 4)
Summary
In this Dart tutorial, we learned about expand() method of Set: the syntax and few working examples with output and detailed explanation for each example.