Dart Set takeWhile()
Syntax & Examples


Set.takeWhile() method

The `takeWhile` method in Dart returns a lazy iterable containing the leading elements from the set that satisfy a given test condition.


Syntax of Set.takeWhile()

The syntax of Set.takeWhile() method is:

 Iterable<E> takeWhile(bool test(E value)) 

This takeWhile() method of Set returns a lazy iterable of the leading elements satisfying test.

Parameters

ParameterOptional/RequiredDescription
testrequiredA function that takes an element of the set as an argument and returns a boolean value.

Return Type

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



✐ Examples

1 Take while element is less than 3 (for integers)

In this example,

  1. We create a Set numbers with elements 1, 2, 3, 4, and 5.
  2. We use the takeWhile() method with a test function that checks if the element is less than 3.
  3. The method returns an iterable of elements that satisfy the test condition.
  4. We print the result to standard output.

Dart Program

void main() {
  Set<int> numbers = {1, 2, 3, 4, 5};
  var result = numbers.takeWhile((element) => element < 3);
  print('Result: $result');
}

Output

Result: (1, 2)

2 Take while element is not 'd' (for characters)

In this example,

  1. We create a Set characters with elements 'a', 'b', 'c', 'd', and 'e'.
  2. We use the takeWhile() method with a test function that checks if the element is not 'd'.
  3. The method returns an iterable of elements that satisfy the test condition.
  4. We print the result to standard output.

Dart Program

void main() {
  Set<String> characters = {'a', 'b', 'c', 'd', 'e'};
  var result = characters.takeWhile((element) => element != 'd');
  print('Result: $result');
}

Output

Result: (a, b, c)

3 Take while length of element is less than 6 (for strings)

In this example,

  1. We create a Set strings with elements 'apple', 'banana', 'cherry', and 'date'.
  2. We use the takeWhile() method with a test function that checks if the length of the element is less than 6.
  3. The method returns an iterable of elements that satisfy the test condition.
  4. We print the result to standard output.

Dart Program

void main() {
  Set<String> strings = {'apple', 'banana', 'cherry', 'date'};
  var result = strings.takeWhile((element) => element.length < 6);
  print('Result: $result');
}

Output

Result: (apple)

Summary

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