Dart – Filter Elements of Set

To filter elements of a Set in Dart, call retainWhere() method and pass the condition that should be satisfied by the elements to remain in the Set. Set.retainWhere(condition) retains only those elements that satisfy the given condition, and removes those elements that do not satisfy the condition.

Syntax

The syntax to call retainWhere() method on Set mySet with condition passed as argument is

mySet.retainWhere(condition)

where the condition is a function that accesses element of the Set via function parameter and returns a boolean value.

Examples

In the following program, we take a Set mySet, with some numbers, and filter only even numbers in the Set.

main.dart

bool isEven(x) {
  if (x % 2 == 0)
    return true;
  else
    return false;
}

void main() {
  Set mySet = {1, 3, 6, 10, 13, 15, 20};
  print('Original Set  : $mySet');
  mySet.retainWhere(isEven);
  print('Filtered Set  : $mySet');
}

Output

Original Set  : {1, 3, 6, 10, 13, 15, 20}
Filtered Set  : {6, 10, 20}

We can also provide a lambda function as argument in the call to retainWhere() method.

main.dart

void main() {
  Set mySet = {1, 3, 6, 10, 13, 15, 20};
  print('Original Set  : $mySet');
  mySet.retainWhere((x) => x % 2 == 0);
  print('Filtered Set  : $mySet');
}

Output

Original Set  : {1, 3, 6, 10, 13, 15, 20}
Filtered Set  : {6, 10, 20}

Conclusion

In this Dart Tutorial, we learned how to filter the elements of a Set in Dart language, with examples.