Dart – Remove Elements from Set based on Condition

To remove elements from a Set that satisfy a given condition, call removeWhere() method and pass the condition that should be satisfied by the elements to be removed from the Set. Set.removeWhere(condition) removes those elements that satisfy the given condition, and retains those elements that do not satisfy the condition.

Syntax

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

mySet.removeWhere(condition)

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

ADVERTISEMENT

Examples

In the following program, we take a Set mySet, with some numbers, and remove odd numbers from the Set.

main.dart

bool isOdd(x) {
  if (x % 2 == 1)
    return true;
  else
    return false;
}

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

Output

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

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

main.dart

void main() {
  Set mySet = {1, 3, 6, 10, 13, 15, 20};
  print('Original Set  : $mySet');
  mySet.removeWhere((x) => x % 2 == 1);
  print('Resulting 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 remove the elements of a Set that satisfy a given condition, with examples.