Flutter學習-day03 Dart List set map進階

Dart三種集合的方法介紹

  • list是有序,數據可重複的集合
  • set是有序,數據不可重複的集合
  • map是無序,鍵不可以重複的集合

 

List數組/集合

  /**
   * list數組
   */
  var list=['1','2','3','4','5','6','7'];
  var addList=['8','9'];
  list.addAll(addList);//數組添加內容
  list.insert(3, 'b');//在第位置上,插入單個元素
  list.insertAll(3, ['d','e','f','g']);//在第位置上,插入一組元素
  list.remove('9');//刪除指定元素
  list.removeAt(2);//刪除指定位置的元素
  list.fillRange(0, 1,'a');//元素替換,替換第0個位置元素
  var length=list.length;//求數組長度
  var newList1=list.reversed.toList();//數組翻轉
  var bools=list.isEmpty;//判斷集合是否爲空
  var bools2=list.isNotEmpty;//判斷集合是否不爲空

  var str=list.join('***');//集合轉字符串 可以用任意字符拼接
  var newList2=str.split('***');//字符串轉集合

  //兩種遍歷方式
  list.forEach((element) {
    
  });

  for (var item in list) {
    
  }

  print('集合輸出 $list');
  print('集合長度 $length');
  print('集合翻轉 $newList1');
  print('集合是否爲空 $bools');
  print('集合是否不爲空 $bools2');
  print('集合轉字符串,可以用任意字符拼接 $str');
  print('字符串轉集合 $newList2');

Map數組/集合 

  var map=new Map();
  map['pos1']='辣條';
  map['pos2']= '100';
  map['pos3']='老虎肉';
  map['pos4']='鴿子肉';
  map['pos5']='西瓜泡泡糖';

  map.addAll({'pos6':'橘子汽水',
  'pos7':['瓜子','杏仁','八寶粥']
  });

  var mapList=map.keys.toList();//獲取map集合所有的鍵,轉成list集合輸出
  var mapList2=map.values.toList();//獲取map集合所有的值,轉成list集合輸出
  print('輸出map集合所有鍵 $mapList');
  print('輸出map集合所有鍵 $mapList2');

  map.forEach((key, value) {
    print("map----"+key+' : '+value);
   });


  //forin循環輸出數據
  for(var item in mapList2){
    print("----"+item);
  }

  var list2=[1,2,3,4,5,6,7,8,9,10];

  //如果所有的數據都滿足條件的就返回true,否則返回false
    var f=list2.every((value){
    return value>0;
  });
  print(f);

 //如果所有的數據至少有一項滿足條件就返回true,否則返回false
  var f2=list2.any((value){
    return value>10;
  });
  print(f2);

  //循環遍歷,輸出滿足條件的數據
  var newList5=list2.where((value){
    return value>5;
  });
  print(newList5.toList());

  //集合進階
 List list3=[
   {
     'province':'河北',
     'city':[
       '石家莊','廊坊','辛集'
     ],
   },   
   
   {
     'province':'北京',
     'city':[
       '朝陽區','海淀區','昌平區'
     ],
   },  
   
    {
     'province':'山東',
     'city':[
       '青島','淄博','濟南'
     ],
   }
 ];

 for(int i=0;i<list3.length;i++){
   print(list3[i]);
 }

  for(int i=0;i<list3.length;i++){
   print(list3[i]['province']+" ");

   for(int j=0;j<list3[i]['city'].length;j++){
     print("   "+list3[i]['city'][j]);
   }

Set數組/集合 

  var set=new Set();
  set.addAll(['11','22','33','44','33','22']);
  print('set集合輸出 $set');

  • Set數組中很多方法沒有,不如list多

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章