Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

splaytreeset
any
dart
communitycreator

How to check if any item of SplayTreeSet matches a test in Dart

Programming Bytes

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 PredicatePredicate is a Functional interface that takes one argument and returns either true or false based on the condition defined function is passed as an argument.

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 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 set contains any element greater than 4
  bool result = set.any( (e)=> e > 4 );
  print('If the set contains any element greater than 4 : $result');

  // check if set contains any negative element 
  result = set.any( (e)=> e < 0 );
  print('If the set contains any negativee element : $result');

}
Using the any element

Explanation

  • 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–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 get true.

  • Line 20: We use the any() method with a predicate function. The predicate function checks if the element is negative. In our case, the set doesn’t contain any negative elements. Hence, we’ll get false.

RELATED TAGS

splaytreeset
any
dart
communitycreator
RELATED COURSES

View all Courses

Keep Exploring