We can use the every()
method to check if all elements of the SplayTreeSet
satisfy the provided test condition.
This method loops through all the elements of the SplayTreeSet
in the iteration order. It checks each element against the test condition.
bool every(bool test(E element));
A
This method returns true
if all of the SplayTreeSet
elements satisfy the provided test condition. Otherwise, false
is returned.
The code below demonstrates the use of the every()
method to check if all items of SplayTreeSet
matches a provided test 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'); // check if all element of set is positive bool result = set.every( (e)=> e >=0 ); print('All element of set is positive : $result'); // check if all element of set is greater than 2 result = set.every( (e)=> e > 2 ); print('If all elements are greater than 2 : $result'); }
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 descending order.
Lines 7 and 11: We add five new elements to the set
. Now, the set is {5,4,3,2,1}
.
Line 16: We use the every()
method with a predicate function. The predicate function checks if the element is positive. In our case, all elements of the set
are positive. Hence, we get true
.
Line 20: We use the every()
method with a predicate function. The predicate function checks if the element is greater than 2. In our case, elements 1 and 2 are not greater than 2. Hence, we get false
.
RELATED TAGS
CONTRIBUTOR
View all Courses