Dart 操作集合
final list = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
forEach
迭代集合的每一个元素
- demo
list.forEach((String it){
print(it);
});
// 等效于
for (var it in list) {
print(it);
}
- 输出结果
flutter: 1
flutter: 2
flutter: 3
flutter: 4
flutter: 5
flutter: 6
flutter: 7
flutter: 8
flutter: 9
flutter: 0
where
返回一个新的
、满足条件
的集合, 并且与原集合顺序保持一致
.
- demo
list.where((String it) {
return int.parse(it) % 2 == 0;
}).forEach((String it) {
print(it);
});
- 输出结果
flutter: 2
flutter: 4
flutter: 6
flutter: 8
flutter: 0
- 优化
where((it) {}
、forEach((it) {}
为函数式, 直接使用链式调用的方式:
// 输出结果同上
list.where((it) => int.parse(it) % 2 == 0).forEach(print);
- 或者使用自定义的方法:
list.where((it) => int.parse(it) % 2 == 0).forEach(customPrint);
void customPrint(String it) {
it += ' - ';
print(it);
}
- 输出结果
flutter: 2 -
flutter: 4 -
flutter: 6 -
flutter: 8 -
flutter: 0 -
whereType
获取指定类型的集合
var list = [1, "a", 2, "b", 3];
var ints = list.whereType<int>();
- ints
flutter: 1
flutter: 2
flutter: 3
skip
跳过, 会从指定index
开始.
- demo
list.skip(3).forEach(print);
- 输出
flutter: 4
flutter: 5
flutter: 6
flutter: 7
flutter: 8
flutter: 9
flutter: 0
take
会获取接下来的N
个值
- demo
// 跳过前三个, 接下来只取3个值
list.skip(3).take(3).forEach(print);
- 输出
flutter: 4
flutter: 5
flutter: 6
TODO
其他方法:
-
fold
-
join
网友评论