使用 '.toList()'
本课属于 Coddy Dart 学习旅程的“逻辑与流程控制”单元。第 12 课,共 65 课。
在列表上使用 map() 和 where() 这类方法时,它们不会返回新的 List,而是返回 Iterable。Iterable 包含你需要的转换后或筛选后的数据,但你通常需要将它转换回 List,才能使用熟悉的列表方法和属性。
.toList() 方法可以将 Iterable 转换回 List。转换后会创建一个新列表,其中包含可迭代对象中的所有元素,让你可以使用熟悉的所有标准列表操作。
List<String> words = ['apple', 'banana', 'cherry', 'date'];
// where() 返回的是 Iterable,不是 List
var longWordsIterable = words.where((word) => word.length > 5);
// 将 Iterable 转换为 List
List<String> longWordsList = longWordsIterable.toList();
print(longWordsList); // ['banana', 'cherry']当你需要对筛选或转换后的数据执行其他列表操作时,这一步转换至关重要。如果没有 .toList(),你处理的就会是 Iterable,它的功能比完整的 List 更有限。
挑战
简单创建一个程序,通过根据类型偏好筛选书籍并将结果转换为列表格式,来管理图书馆的书籍推荐系统。你的程序应:
- 读取一个表示图书馆名称的字符串输入
- 读取多个表示书名的字符串输入(收到空字符串时,输入结束)
- 读取多个与各书名对应、表示书籍类型的字符串输入(收到空字符串时,输入结束)
- 读取一个表示要筛选的偏好类型的字符串输入
- 使用
where()方法筛选出符合偏好类型的书籍 - 使用
toList()方法将筛选后的可迭代对象转换为列表 - 按照下方显示的确切格式打印推荐结果
例如,如果图书馆名称是 "City Library",书籍是 "The Great Gatsby"、"Dune"、"Pride and Prejudice"、"1984",类型是 "Fiction"、"Science Fiction"、"Romance"、"Fiction",偏好类型是 "Fiction",你的程序应输出:
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 ready如果图书馆名称是 "School Library",书籍是 "Harry Potter"、"Lord of the Rings",类型是 "Fantasy"、"Fantasy",偏好类型是 "Mystery",你的程序应输出:
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 ready如果图书馆名称是 "Community Library",书籍是 "To Kill a Mockingbird",类型是 "Classic",偏好类型是 "Classic",你的程序应输出:
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 ready你的程序必须使用 where() 方法,根据书籍类型是否与偏好类型匹配来筛选书籍,然后使用 toList() 方法将得到的可迭代对象转换为列表。筛选后的可迭代对象应以圆括号格式显示,最终列表应以方括号格式显示。
亲手试试
import 'dart:io';
void main() {
// 读取图书馆名称
String? libraryName = stdin.readLineSync();
// 读取书名,直到遇到空字符串
List<String> books = [];
while (true) {
String? book = stdin.readLineSync();
if (book == null || book.isEmpty) break;
books.add(book);
}
// 读取图书类型,直到遇到空字符串
List<String> genres = [];
while (true) {
String? genre = stdin.readLineSync();
if (genre == null || genre.isEmpty) break;
genres.add(genre);
}
// 读取偏好的图书类型
String? preferredGenre = stdin.readLineSync();
// TODO: 在下方编写你的代码
// 使用 where() 方法按偏好的图书类型筛选图书
// 使用 toList() 方法将筛选后的可迭代对象转换为列表
// 按要求的格式输出结果
print('Library: $libraryName');
print('All books: $books');
print('All genres: $genres');
print('Filtering by genre: $preferredGenre');
// 输出筛选后的图书(可迭代对象)和推荐图书(列表)
// 输出推荐总数和状态
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程控制中的所有课
自己练习: Dart 在线编译器