A
SplayTreeSet
is a set of objects that can be ordered relative to each other.
We can use the removeWhere
method to remove all the elements of the set that satisfy the provided test
condition.
void removeWhere( bool test(Element e) )
This method takes a test
function, which takes one argument (current element value) and returns a boolean value. This method is invoked for each element of the set
.
The removeWhere
method will iterate the set
and invoke the test
function. If the test
function returns True
, then the current element will be removed from the set
.
This method doesn’t return any value(s).
The code written below demonstrates how we can use the removeWhere
method to remove all the elements of the SplayTreeSet
that satisfy a given condition:
import 'dart:collection'; void main() { //create a new SplayTreeSet which can have int type elements SplayTreeSet set = new SplayTreeSet<int>((a,b) => b.compareTo(a)); // add five elements to the set set.add(5); set.add(4); set.add(3); set.add(2); set.add(1); print('The set is $set'); // Remove the entry with odd value set.removeWhere((element){ return element % 2 != 0; }); print('The set is $set'); }
Line 1: We import the collection
library.
Line 4: We create a new SplayTreeSet
object with the name set
. We pass a compare
function as an argument. This function is used for maintaining the order of the set
elements. In our case, the compare
function orders the elements in a descending order.
Lines 7–11: We add five new elements to the set
. Now, the set is {5,4,3,2,1}
.
Line 16: We use the removeWhere
method with a test
function as an argument. The test
function returns True
if the element is an odd
number. In our case, the elements 5,3,1
are odd numbers, so they are removed from the set
. After the removal of the odd number values, the set
is {4,2}
.
RELATED TAGS
CONTRIBUTOR
View all Courses