Checking Conditions with 'any'
Part of the Logic & Flow section of Coddy's Dart journey — lesson 13 of 65.
Sometimes you need to check if at least one element in a list meets a specific condition, without having to examine every single element. The any() method provides an efficient way to do this by returning true as soon as it finds the first element that satisfies your test condition.
The any() method takes a test function that returns true or false for each element. If any element passes the test, any() immediately returns true. If no elements pass the test after checking the entire list, it returns false.
List<double> prices = [15.99, 45.50, 120.00, 8.75];
// Check if any item costs more than $100
bool hasExpensiveItem = prices.any((price) => price > 100);
print(hasExpensiveItem); // trueThis method is particularly useful for validation scenarios where you need to know if at least one item meets certain criteria. The any() method stops checking as soon as it finds a match, making it more efficient than manually looping through the entire list when you only need to know if something exists.
Challenge
EasyCreate a program that manages a security system by checking if any sensor in a building has detected suspicious activity. Your program should:
- Read a string input representing the building name
- Read multiple integer inputs representing sensor readings from different floors (the input will end when you receive
-1) - Read an integer input representing the alert threshold value
- Use the
any()method to check if any sensor reading is greater than or equal to the alert threshold - Print the security monitoring results in the exact format shown below
For example, if the building name is "Office Tower", the sensor readings are 15, 23, 8, 45, 12, and the alert threshold is 40, your program should output:
Building: Office Tower
Sensor readings: [15, 23, 8, 45, 12]
Alert threshold: 40
Checking for readings >= 40
Alert triggered: true
Status: Security breach detected - immediate response requiredIf the building name is "Shopping Mall", the sensor readings are 18, 25, 12, 30, and the alert threshold is 50, your program should output:
Building: Shopping Mall
Sensor readings: [18, 25, 12, 30]
Alert threshold: 50
Checking for readings >= 50
Alert triggered: false
Status: All systems normal - no threats detectedIf the building name is "Warehouse", the sensor readings are 75, 82, and the alert threshold is 70, your program should output:
Building: Warehouse
Sensor readings: [75, 82]
Alert threshold: 70
Checking for readings >= 70
Alert triggered: true
Status: Security breach detected - immediate response requiredYour program must use the any() method to check if any sensor reading is greater than or equal to the alert threshold. Display "Security breach detected - immediate response required" if any sensor triggers the alert, or "All systems normal - no threats detected" if no sensors exceed the threshold.
Cheat sheet
The any() method checks if at least one element in a list meets a specific condition. It returns true as soon as it finds the first element that satisfies the test condition, or false if no elements pass the test.
List<double> prices = [15.99, 45.50, 120.00, 8.75];
// Check if any item costs more than $100
bool hasExpensiveItem = prices.any((price) => price > 100);
print(hasExpensiveItem); // trueThe any() method is efficient because it stops checking as soon as it finds a match, making it ideal for validation scenarios where you only need to know if something exists.
Try it yourself
import 'dart:io';
void main() {
// Read building name
String? buildingName = stdin.readLineSync();
// Read sensor readings until -1 is encountered
List<int> sensorReadings = [];
while (true) {
int reading = int.parse(stdin.readLineSync()!);
if (reading == -1) {
break;
}
sensorReadings.add(reading);
}
// Read alert threshold
int alertThreshold = int.parse(stdin.readLineSync()!);
// TODO: Write your code below
// Use the any() method to check if any sensor reading is >= alert threshold
// Print the results in the required format
print('Building: $buildingName');
print('Sensor readings: $sensorReadings');
print('Alert threshold: $alertThreshold');
print('Checking for readings >= $alertThreshold');
// Print alert triggered result and status message
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List