Checking for Elements in a Set
Part of the Logic & Flow section of Coddy's Dart journey — lesson 20 of 65.
When working with a Set, you'll frequently need to check whether a specific element exists in the collection. The contains() method provides a simple and efficient way to perform this check, returning true if the element is found and false if it's not.
One of the key advantages of using contains() with a Set is its exceptional performance. Unlike searching through a List where each element might need to be checked one by one, Set operations are optimized for fast lookups, making contains() very efficient even with large collections.
Set<String> ingredients = {'flour', 'sugar', 'eggs', 'butter'};
// Check if specific ingredients are available
bool hasFlour = ingredients.contains('flour');
bool hasMilk = ingredients.contains('milk');
print(hasFlour); // true
print(hasMilk); // falseThis method is particularly useful when you need to validate data, check prerequisites, or filter information based on membership in a specific collection. The boolean result makes it perfect for use in conditional statements and logical operations.
Challenge
EasyCreate a program that manages a recipe validation system by checking if specific ingredients are available in the kitchen pantry. Your program should:
- Read a string input representing the recipe name
- Read multiple string inputs representing available pantry ingredients (the input will end when you receive
"pantry_done") - Read multiple string inputs representing required recipe ingredients (the input will end when you receive
"recipe_done") - Create a Set with the available pantry ingredients
- Use the
contains()method to check if each required ingredient is available in the pantry - Print the recipe validation results in the exact format shown below
For example, if the recipe name is "Chocolate Chip Cookies", the pantry ingredients are "flour", "sugar", "eggs", "butter", "vanilla", and the required ingredients are "flour", "sugar", "chocolate chips", "butter", your program should output:
Recipe: Chocolate Chip Cookies
Pantry ingredients: {flour, sugar, eggs, butter, vanilla}
Required ingredients: [flour, sugar, chocolate chips, butter]
Checking ingredient availability:
- flour: Available
- sugar: Available
- chocolate chips: Missing
- butter: Available
Missing ingredients: [chocolate chips]
Status: Cannot make recipe - missing 1 ingredient(s)If the recipe name is "Scrambled Eggs", the pantry ingredients are "eggs", "butter", "salt", "pepper", and the required ingredients are "eggs", "butter", "salt", your program should output:
Recipe: Scrambled Eggs
Pantry ingredients: {eggs, butter, salt, pepper}
Required ingredients: [eggs, butter, salt]
Checking ingredient availability:
- eggs: Available
- butter: Available
- salt: Available
Missing ingredients: []
Status: Ready to cook - all ingredients availableIf the recipe name is "Fruit Salad", the pantry ingredients are "apples", "bananas", and the required ingredients are "apples", "oranges", "grapes", "honey", your program should output:
Recipe: Fruit Salad
Pantry ingredients: {apples, bananas}
Required ingredients: [apples, oranges, grapes, honey]
Checking ingredient availability:
- apples: Available
- oranges: Missing
- grapes: Missing
- honey: Missing
Missing ingredients: [oranges, grapes, honey]
Status: Cannot make recipe - missing 3 ingredient(s)Your program must use the contains() method to check each required ingredient against the pantry Set. Store the required ingredients in a list to maintain the order for checking, and collect any missing ingredients in a separate list. If all ingredients are available, show "Ready to cook - all ingredients available" as the status. If any ingredients are missing, show "Cannot make recipe - missing X ingredient(s)" where X is the count of missing ingredients.
Cheat sheet
Use the contains() method to check if a specific element exists in a Set. It returns true if the element is found and false if it's not:
Set<String> ingredients = {'flour', 'sugar', 'eggs', 'butter'};
bool hasFlour = ingredients.contains('flour');
bool hasMilk = ingredients.contains('milk');
print(hasFlour); // true
print(hasMilk); // falseThe contains() method is highly efficient with Set collections, making it ideal for fast lookups even with large datasets. It's particularly useful for validation, checking prerequisites, and conditional operations.
Try it yourself
import 'dart:io';
void main() {
// Read recipe name
String? recipeName = stdin.readLineSync();
// Read pantry ingredients until "pantry_done"
Set<String> pantryIngredients = <String>{};
String? pantryInput;
while ((pantryInput = stdin.readLineSync()) != "pantry_done") {
if (pantryInput != null) {
pantryIngredients.add(pantryInput);
}
}
// Read required ingredients until "recipe_done"
List<String> requiredIngredients = <String>[];
String? recipeInput;
while ((recipeInput = stdin.readLineSync()) != "recipe_done") {
if (recipeInput != null) {
requiredIngredients.add(recipeInput);
}
}
// TODO: Write your code below
// Use pantryIngredients.contains() to check each required ingredient
// Create a list to store missing ingredients
// Check availability and print results in the required format
// Print the results (replace with your implementation)
print("Recipe: $recipeName");
print("Pantry ingredients: $pantryIngredients");
print("Required ingredients: $requiredIngredients");
}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