集合数据遍历
在类型介绍中我们说过了list map set 的创建 添加 取出数据 在这里就说下如何遍历list map set
List遍历
-
创建一个List
-
var list=[1,2,3.4]
-
-
遍历List
-
通过for each
-
list.forEach((dynamic i) => print(i)); list.forEach((i) { print(i); });
-
-
通过迭代器
Iterable
-
循环遍历 list set 均实现了Iterator map可以根据key 和value 获取Iterable
-
Iterator it = list.iterator; while (it.moveNext()) { print(it.current); }
-
-
通过下标索引
-
for (int i = 0; i < list.length; i++) { print(list[i].toString() + "for 循环输出"); }
-
-
Map 遍历
-
创建Map集合并添加数据
-
Map<String, String> mapv = { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3', };
-
-
遍历map
-
通过for each
-
mapv.forEach((k, v) { print(k + v); });
-
-
迭代器
-
通过key的迭代器取出value
-
Iterator itKeys = map.keys.toList().iterator; while (itKeys.moveNext()) { print(map[itKeys.current]); }
-
-
通过value迭代器取
-
Iterator itValues = map.values.toList().iterator; while (itValues.moveNext()) { print(itValues.current); }
-
-
-
set遍历
-
创建set 添加数据
-
Set setv = new Set(); setv.addAll([1,2,3,4,5,6]);
-
-
遍历Set
-
通过迭代器
-
Iterator it = setv.iterator; while (it.moveNext()) { print(it.current); }
-
-
通过foreach
-
setv.forEach((i){ print(i); });
-
-