Dart Set where()
Syntax & Examples


Set.where() method

The `where` method in Dart returns a new lazy Iterable containing all elements of the set that satisfy the provided predicate test.


Syntax of Set.where()

The syntax of Set.where() method is:

 Iterable<E> where(bool test(E element)) 

This where() method of Set returns a new lazy Iterable with all elements that satisfy the predicate test.

Parameters

ParameterOptional/RequiredDescription
testrequiredThe function used to test elements of the set.

Return Type

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



✐ Examples

1 Filter even integers

In this example,

  1. We create a Set set containing integers.
  2. We use the where() method with a test function that checks if each element is even.
  3. We print the filtered lazy Iterable to standard output.

Dart Program

void main() {
  Set<int> set = {1, 2, 3, 4, 5};
  Iterable<int> filteredSet = set.where((element) => element % 2 == 0);
  print('Filtered set elements: $filteredSet');
}

Output

Filtered set elements: (2, 4)

2 Filter strings containing 'a'

In this example,

  1. We create a Set set containing strings.
  2. We use the where() method with a test function that checks if each string contains the character 'a'.
  3. We print the filtered lazy Iterable to standard output.

Dart Program

void main() {
  Set<String> set = {'apple', 'banana', 'orange', 'berry', 'cherry'};
  Iterable<String> filteredSet = set.where((element) => element.contains('a'));
  print('Filtered set elements: $filteredSet');
}

Output

Filtered set elements: (apple, banana, orange)

Summary

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