Sorting a List
Part of the Logic & Flow section of Coddy's Dart journey — lesson 7 of 65.
When you need to organize the elements in a list, Dart provides the sort() method that arranges elements in ascending order. This method is particularly useful for putting names in alphabetical order or numbers from smallest to largest.
The sort() method modifies the original list directly rather than creating a new sorted list. When you call sort() on a list, it rearranges the existing elements in place.
List<String> names = ['Charlie', 'Alice', 'Bob'];
names.sort();
print(names); // ['Alice', 'Bob', 'Charlie']
List<int> scores = [85, 92, 78, 96];
scores.sort();
print(scores); // [78, 85, 92, 96]The sort() method works automatically for common data types like strings and numbers. For strings, it sorts alphabetically, while for numbers, it sorts from lowest to highest. This makes it a straightforward tool for organizing your data whenever you need elements in a predictable order.
Challenge
EasyCreate a program that manages a restaurant menu system by organizing dishes in different categories. Your program should:
- Read a string input representing the restaurant name
- Read multiple string inputs representing dish names (the input will end when you receive an empty string)
- Use the
sort()method to arrange the dishes in alphabetical order - Print the organized menu in the exact format shown below
For example, if the restaurant name is "Bella Vista" and the dishes are "Pasta Carbonara", "Caesar Salad", "Grilled Salmon", "Apple Pie", your program should output:
Restaurant: Bella Vista
Original menu: [Pasta Carbonara, Caesar Salad, Grilled Salmon, Apple Pie]
Sorted menu: [Apple Pie, Caesar Salad, Grilled Salmon, Pasta Carbonara]
Total dishes: 4
Status: Menu organized alphabeticallyIf the restaurant name is "Quick Bites" and the dishes are "Burger", "Pizza", "Sandwich", your program should output:
Restaurant: Quick Bites
Original menu: [Burger, Pizza, Sandwich]
Sorted menu: [Burger, Pizza, Sandwich]
Total dishes: 3
Status: Menu organized alphabeticallyIf the restaurant name is "Cafe Corner" and only one dish "Coffee" is provided, your program should output:
Restaurant: Cafe Corner
Original menu: [Coffee]
Sorted menu: [Coffee]
Total dishes: 1
Status: Menu organized alphabeticallyYour program must use the sort() method to arrange the dishes alphabetically. Remember that sort() modifies the original list in place, so you'll need to create a copy of the original list before sorting if you want to display both the original and sorted versions.
Cheat sheet
The sort() method arranges list elements in ascending order and modifies the original list directly:
List<String> names = ['Charlie', 'Alice', 'Bob'];
names.sort();
print(names); // ['Alice', 'Bob', 'Charlie']
List<int> scores = [85, 92, 78, 96];
scores.sort();
print(scores); // [78, 85, 92, 96]For strings, sort() arranges elements alphabetically. For numbers, it sorts from lowest to highest. Since sort() modifies the original list in place, create a copy first if you need to preserve the original order.
Try it yourself
import 'dart:io';
void main() {
// Read restaurant name
String? restaurantName = stdin.readLineSync();
// Read dish names until empty string
List<String> dishes = [];
String? dish;
while ((dish = stdin.readLineSync()) != null && dish!.isNotEmpty) {
dishes.add(dish);
}
// TODO: Write your code below
// Create a copy of the original list and sort it
// Calculate total dishes
// Print the required output format
// Output the results
// print("Restaurant: $restaurantName");
// print("Original menu: $dishes");
// print("Sorted menu: $sortedDishes");
// print("Total dishes: $totalDishes");
// print("Status: Menu organized alphabetically");
}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