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

ParameterOptional/RequiredDescription
frequiredA 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,

  1. We create a Set set containing strings.
  2. We use the expand() method with a function that splits each string into individual characters.
  3. 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,

  1. We create a Set set containing integers.
  2. We use the expand() method with a function that creates consecutive pairs from each integer.
  3. 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.