dart 01.1 List、set、map

集合數據遍歷

在類型介紹中我們說過了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);
          });
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章