Dart Set take()
Syntax & Examples


Set.take() method

The `take` method in Dart returns a lazy iterable containing the first `count` elements of the set.


Syntax of Set.take()

The syntax of Set.take() method is:

 Iterable<E> take(int count) 

This take() method of Set returns a lazy iterable of the count first elements of this iterable.

Parameters

ParameterOptional/RequiredDescription
countrequiredThe number of elements to take from the beginning of the set.

Return Type

Set.take() returns value of type Iterable<E>.



✐ Examples

1 Take first 3 integers

In this example,

  1. We create a Set set containing integers.
  2. We use the take() method with a count of 3 to take the first 3 elements from the set.
  3. We print the lazy iterable containing the taken elements to standard output.

Dart Program

void main() {
  Set<int> set = {1, 2, 3, 4, 5};
  Iterable<int> takenSet = set.take(3);
  print('Taken set elements: $takenSet');
}

Output

Taken set elements: (1, 2, 3)

2 Take first 2 strings

In this example,

  1. We create a Set set containing strings.
  2. We use the take() method with a count of 2 to take the first 2 elements from the set.
  3. We print the lazy iterable containing the taken elements to standard output.

Dart Program

void main() {
  Set<String> set = {'apple', 'banana', 'orange'};
  Iterable<String> takenSet = set.take(2);
  print('Taken set elements: $takenSet');
}

Output

Taken set elements: (apple, banana)

Summary

In this Dart tutorial, we learned about take() method of Set: the syntax and few working examples with output and detailed explanation for each example.