Dart Set removeWhere()
Syntax & Examples
Set.removeWhere() method
The `removeWhere` method in Dart removes all elements from the set that satisfy a given test.
Syntax of Set.removeWhere()
The syntax of Set.removeWhere() method is:
void removeWhere(bool test(E element))
This removeWhere() method of Set removes all elements of this set that satisfy test.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
test | required | A function that takes an element of the set as input and returns a boolean value. If the return value is true, the element is removed from the set. |
Return Type
Set.removeWhere() returns value of type void
.
✐ Examples
1 Remove even numbers from set
In this example,
- We create a Set
set
containing integers. - We use the
removeWhere()
method with a test function that removes elements divisible by 2 (i.e., even numbers). - We print the resulting Set to standard output.
Dart Program
void main() {
Set<int> set = {1, 2, 3, 4};
set.removeWhere((element) => element % 2 == 0);
print('Set after removing even numbers: $set');
}
Output
Set after removing even numbers: {1, 3}
2 Remove elements containing letter 'a' from set
In this example,
- We create a Set
set
containing strings. - We use the
removeWhere()
method with a test function that removes elements containing the letter 'a'. - We print the resulting Set to standard output.
Dart Program
void main() {
Set<String> set = {'apple', 'banana', 'orange', 'berry'};
set.removeWhere((element) => element.contains('a'));
print('Set after removing elements containing letter a: $set');
}
Output
Set after removing elements containing letter a: {berry}
Summary
In this Dart tutorial, we learned about removeWhere() method of Set: the syntax and few working examples with output and detailed explanation for each example.