Iterating Over a Map
Part of the Logic & Flow section of Coddy's Dart journey — lesson 26 of 65.
When working with Map collections, you often need to process every key-value pair. The forEach method provides a clean way to iterate through all entries in a map, giving you access to both the key and its corresponding value.
The forEach method takes a function as an argument. This function receives two parameters: the key and the value for each entry in the map. The method automatically calls your function once for every key-value pair in the map.
Map<String, int> studentScores = {
'Alice': 85,
'Bob': 92,
'Charlie': 78
};
studentScores.forEach((name, score) {
print('$name scored $score points');
});
// Output:
// Alice scored 85 points
// Bob scored 92 points
// Charlie scored 78 pointsThis approach is much more convenient than manually accessing each key or trying to loop through the map using other methods. The forEach method handles all the iteration logic for you, making your code cleaner and more readable when you need to process every entry in a map.
Challenge
EasyCreate a program that manages a restaurant's daily sales reporting system by analyzing menu items and their sales data. Your program should:
- Read a string input representing the restaurant name
- Read multiple pairs of inputs representing menu items and their sales amounts (the input will end when you receive
"sales_done") - Create a Map to store each menu item as the key and its sales amount as the value
- Use the
forEachmethod to iterate through the sales data and calculate the total revenue - Use the
forEachmethod again to identify the best-selling item (highest sales amount) - Print the sales report in the exact format shown below
For example, if the restaurant name is "Mario's Pizza" and the sales data includes "Margherita Pizza" with 450, "Caesar Salad" with 280, "Garlic Bread" with 320, "Tiramisu" with 180, your program should output:
Restaurant: Mario's Pizza
Daily Sales Report:
Margherita Pizza: $450
Caesar Salad: $280
Garlic Bread: $320
Tiramisu: $180
Total Revenue: $1230
Best Selling Item: Margherita Pizza ($450)
Status: Sales report generated successfullyIf the restaurant name is "Sushi Express" and the sales data includes "California Roll" with 380, "Salmon Sashimi" with 520, "Miso Soup" with 150, your program should output:
Restaurant: Sushi Express
Daily Sales Report:
California Roll: $380
Salmon Sashimi: $520
Miso Soup: $150
Total Revenue: $1050
Best Selling Item: Salmon Sashimi ($520)
Status: Sales report generated successfullyIf the restaurant name is "Burger Palace" and the sales data includes "Classic Burger" with 600, "French Fries" with 400, "Milkshake" with 250, "Onion Rings" with 180, your program should output:
Restaurant: Burger Palace
Daily Sales Report:
Classic Burger: $600
French Fries: $400
Milkshake: $250
Onion Rings: $180
Total Revenue: $1430
Best Selling Item: Classic Burger ($600)
Status: Sales report generated successfullyYour program must use the forEach method to iterate through the Map entries. First, use forEach to display each menu item and its sales amount, while also calculating the total revenue. Then use forEach again to find the item with the highest sales amount. The input format will be: restaurant name, then alternating menu item names and sales amounts (as strings that need to be converted to integers), ending with "sales_done".
Cheat sheet
The forEach method allows you to iterate through all key-value pairs in a Map. It takes a function that receives two parameters: the key and the value for each entry.
Map<String, int> studentScores = {
'Alice': 85,
'Bob': 92,
'Charlie': 78
};
studentScores.forEach((name, score) {
print('$name scored $score points');
});
// Output:
// Alice scored 85 points
// Bob scored 92 points
// Charlie scored 78 pointsThe forEach method automatically calls your function once for every key-value pair in the map, making it convenient for processing all entries without manual iteration logic.
Try it yourself
import 'dart:io';
void main() {
// Read restaurant name
String? restaurantName = stdin.readLineSync();
// Create a Map to store menu items and their sales amounts
Map<String, int> salesData = {};
// Read menu items and sales amounts until "sales_done"
while (true) {
String? input = stdin.readLineSync();
if (input == "sales_done") {
break;
}
String menuItem = input!;
String? salesAmountStr = stdin.readLineSync();
int salesAmount = int.parse(salesAmountStr!);
salesData[menuItem] = salesAmount;
}
// TODO: Write your code below
// Use forEach to calculate total revenue and display sales data
// Use forEach again to find the best-selling item
// Print the sales report in the required format
print("Restaurant: $restaurantName");
print("Daily Sales Report:");
// Display each item and calculate total
// Find and display best selling item
// Display total revenue and status
}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