Using '.toList()'
Part of the Logic & Flow section of Coddy's Dart journey — lesson 12 of 65.
When you use methods like map() and where() on a list, they don't return a new List - they return an Iterable. While an Iterable contains the transformed or filtered data you want, you often need to convert it back into a List to use familiar list methods and properties.
The .toList() method converts an Iterable back into a List. This conversion creates a new list containing all the elements from the iterable, giving you access to all the standard list operations you're used to.
List<String> words = ['apple', 'banana', 'cherry', 'date'];
// where() returns an Iterable, not a List
var longWordsIterable = words.where((word) => word.length > 5);
// Convert the Iterable to a List
List<String> longWordsList = longWordsIterable.toList();
print(longWordsList); // ['banana', 'cherry']This conversion step is essential when you need to perform additional list operations on your filtered or transformed data. Without .toList(), you'd be working with an Iterable, which has more limited functionality than a full List.
Challenge
EasyCreate a program that manages a library book recommendation system by filtering books based on genre preferences and converting the results into a proper list format. Your program should:
- Read a string input representing the library name
- Read multiple string inputs representing book titles (the input will end when you receive an empty string)
- Read multiple string inputs representing book genres corresponding to each title (the input will end when you receive an empty string)
- Read a string input representing the preferred genre to filter by
- Use the
where()method to filter books that match the preferred genre - Use the
toList()method to convert the filtered iterable into a proper list - Print the recommendation results in the exact format shown below
For example, if the library name is "City Library", the books are "The Great Gatsby", "Dune", "Pride and Prejudice", "1984", the genres are "Fiction", "Science Fiction", "Romance", "Fiction", and the preferred genre is "Fiction", your program should output:
Library: City Library
All books: [The Great Gatsby, Dune, Pride and Prejudice, 1984]
All genres: [Fiction, Science Fiction, Romance, Fiction]
Filtering by genre: Fiction
Filtered books (iterable): (The Great Gatsby, 1984)
Recommended books (list): [The Great Gatsby, 1984]
Total recommendations: 2
Status: Recommendations readyIf the library name is "School Library", the books are "Harry Potter", "Lord of the Rings", the genres are "Fantasy", "Fantasy", and the preferred genre is "Mystery", your program should output:
Library: School Library
All books: [Harry Potter, Lord of the Rings]
All genres: [Fantasy, Fantasy]
Filtering by genre: Mystery
Filtered books (iterable): ()
Recommended books (list): []
Total recommendations: 0
Status: Recommendations readyIf the library name is "Community Library", the books are "To Kill a Mockingbird", the genres are "Classic", and the preferred genre is "Classic", your program should output:
Library: Community Library
All books: [To Kill a Mockingbird]
All genres: [Classic]
Filtering by genre: Classic
Filtered books (iterable): (To Kill a Mockingbird)
Recommended books (list): [To Kill a Mockingbird]
Total recommendations: 1
Status: Recommendations readyYour program must use the where() method to filter books by matching their genre with the preferred genre, then use the toList() method to convert the resulting iterable into a list. The filtered iterable should be displayed in parentheses format, while the final list should be displayed in square brackets format.
Cheat sheet
Methods like map() and where() return an Iterable, not a List. Use .toList() to convert an Iterable back into a List:
List<String> words = ['apple', 'banana', 'cherry', 'date'];
// where() returns an Iterable, not a List
var longWordsIterable = words.where((word) => word.length > 5);
// Convert the Iterable to a List
List<String> longWordsList = longWordsIterable.toList();
print(longWordsList); // ['banana', 'cherry']This conversion is essential when you need to perform additional list operations on filtered or transformed data.
Try it yourself
import 'dart:io';
void main() {
// Read library name
String? libraryName = stdin.readLineSync();
// Read book titles until empty string
List<String> books = [];
while (true) {
String? book = stdin.readLineSync();
if (book == null || book.isEmpty) break;
books.add(book);
}
// Read book genres until empty string
List<String> genres = [];
while (true) {
String? genre = stdin.readLineSync();
if (genre == null || genre.isEmpty) break;
genres.add(genre);
}
// Read preferred genre
String? preferredGenre = stdin.readLineSync();
// TODO: Write your code below
// Use where() method to filter books by preferred genre
// Use toList() method to convert the filtered iterable to a list
// Print the results in the required format
print('Library: $libraryName');
print('All books: $books');
print('All genres: $genres');
print('Filtering by genre: $preferredGenre');
// Print filtered books (iterable) and recommended books (list)
// Print total recommendations 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