How to check if any item of SplayTreeSet matches a test in Dart
Overview
We can use the any() method to check if any element of the SplayTreeSet satisfies 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.
Syntax
bool any(bool test(E element));
Parameter
A
Return value
This method returns true if any of the SplayTreeSet elements satisfies the provided test condition. Otherwise, false will be returned.
Example
The code below demonstrates how to use the any() method to check if any item of SplayTreeSet matches a provided test condition:
import 'dart:collection';void main() {//create a new SplayTreeSet which can have int type elementsSplayTreeSet set = new SplayTreeSet<int>((a,b) => b.compareTo(a));// add five elements to the setset.add(5);set.add(4);set.add(3);set.add(2);set.add(1);print('The set is $set');// check if set contains any element greater than 4bool result = set.any( (e)=> e > 4 );print('If the set contains any element greater than 4 : $result');// check if set contains any negative elementresult = set.any( (e)=> e < 0 );print('If the set contains any negativee element : $result');}
Explanation
-
Line 1: We import the
collectionlibrary. -
Line 4: We create a new
SplayTreeSetobject with the nameset. We pass acomparefunction as an argument. This function is used for maintaining the order of thesetelements. In our case, thecomparefunction orders the elements in 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
any()method with a predicate function. The predicate function checks if the element is greater than 4. In our case, the set contains element 5, which is greater than 4. Hence, we will gettrue. -
Line 20: We use the
any()method with a predicate function. The predicate function checks if the element is negative. In our case, thesetdoesn’t contain any negative elements. Hence, we’ll getfalse.