Related Tags

dart
set
any
communitycreator

# How to check if any of Dart's set elements matches a condition

Programming Bytes

### Overview

The any() method checks if any element of the set satisfies the provided test condition.

This method loops through all the elements of the set in the iteration order. It checks each element against the test condition.

### Syntax

bool any(bool test(E element));
Syntax of any() method

### Argument

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 set elements satisfies the passed test condition. Otherwise, false will be returned.

### Code

The code below demonstrates the use of the any() method:

import 'dart:collection';
void main() {
// create a set

// add 3 elements to the set

print('The set is : $set'); // check if set contains any element greater than 25 bool result = set.any( (e)=> e > 25 ); print('If the set contains any element greater than 25 :$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() method to check if one of the elements of the set satisfies the test condition

### Explanation

In the above code:

• Line 1: We import the collection library.
• Line 4: We create a LinkedHashSet with namedset.
• Lines 7-8: We use the add() method to add three elements 10, 20, 30 to the set. Now, the set is {10, 20, 30}.
• Line 13: We use the any() method with a predicate function. The predicate function checks if the element is greater than 25. In our case, the set contains the element 30, which is greater than 25. Hence, we will get true.
• Line 17: 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 will get false.

RELATED TAGS

dart
set
any
communitycreator

CONTRIBUTOR

Programming Bytes
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time