Dart's Dictionary (Map) Related Methods

I. Overview    

  Generally, Map is a key-value pair relevant objects, keys and values ​​can be any type of object. Each key only once, but a value can occur more than once. Mapping is a dynamic collection. In other words, Maps can grow and shrink at runtime. dart: core library of Map class provides the same support.

Second, the statement

  • Do not specify generic (in a conventional manner, does not specify any type, then the type of testMap KV are dynamic)
  •     // direct assignment 
        var MAP1 = { 'AA': 'AAA', 'BB': 22 is, 'CC': to true }; 
        the Map MAP2 = { 'A': 'A1', 'B': 'B1'};  
    // indirect assignment 
        var = MAP3 new new the Map (); 
        MAP3 [ 'AA'] = 'AAA' ; 
        the Map MAP4 = new new the Map (); 
        MAP4 [ 'A'] = 'AAA';
  • Generic specified (the example below indicates the type of Map <String, String>, map the initialization type Map <String, String>, if the type does not match or is not compatible will cause it Crash)
        //直接赋值
        var map1 = <String,String>{'aa':'aaa','bb':'22','cc':'333'};
        Map map2 = <String,String>{'a':'a1','b':'b1','c':'c1'};
        
        //间接赋值
        var map3 = new Map<String,String>();
        map3['aa'] = 'aaa';
        Map map4 = new Map<String,String>();
        map4['a'] = 'a1';

 

  • Copy of the form
      / ** 
       * not use the type of operator, initialize a new map from another map, the map in this case containing the other resources in the new map 
       * / 
      the Map MAP1 = { 'A': 'A1', 'B' : 'B1', 'C': 'C1' }; 
      the Map MAP2 = Map.castFrom (MAP1); 
      Print (MAP2); 
    
      / ** 
       * initialize the mandatory use of the specified type Map 
       * the following example shows the type of testMap1 <num , String>, castFrom initialized when the map Map of type <int, String> 
       * If the types do not match or incompatible will cause it crashh 
       * / 
      Map < int , String> = {MAP3. 1: 'a', 2: 'B',. 3: 'C' }; 
      the Map MAP4 = Map.castFrom <NUM, String> (MAP3); // this line of code errors, mainly testMap is <dynamic, dynamic> type, but there need is <int, String> type Map 
      the Map MAP5 = the Map.castFrom<String,String>(map3);//This line of code will be wrong, because they can not be <String, String> is converted to the type of map <int, String> type of map 
      the Map MAP6 = Map.castFrom < int , String> (MAP3); // correct
  • Create an immutable Map
    Map map6 = const {'one':'Android','two':'IOS','three':'flutter'};
      // Create the MAP6 destination (copy) the new unmodifiable map7
      the Map map7 = Map.unmodifiable (MAP6);
      Print (map7); 
      // Output: {one: Android, two: IOS, three: flutter}
  • To create a map based on key value list provided;
    List<String> keys = ['one','two']; 
    List<String> values = ['Android','IOS'];
    Map map9 = Map.fromIterables(keys, values);
    print(map9);

Third, property

  Map<String,int> map6 = {"a":1,"b":2};
  •   length
    Print (map6.length); // 2 length
  • isNotEmpty
    Print (map6.isNotEmpty); // to true whether or not empty
  • isEmpty
    Print (map6.isEmpty); // false is empty   
  • keys
    Print (map6.keys); // (A, B) a set of Key
  • values
    Print (map6.values); // (. 1, 2) of the set value
  • entries
    Print (map6.entries); // (the MapEntry (A:. 1), the MapEntry (B: 2)) to the set of keys of the map iterations 

Fourth, the method

  • increase
    • Add a key-value  

       Map <String, int> map7 = { "A":. 1, "B": 2, "C":. 3, "D":. 4, "E":. 5};
      // add a value Key
       map7 [ " f "] = 6; // add a nonexistent Key
       Print (map7); // {a:. 1, B: 2, C:. 3, D:. 4, E:. 5, F:}. 6 

  • change
    • Modify a key's value
      Map<String,int> map8 = {"a":1,"b":2,"c":3,"d":4,"e":5};
      map8["a"] = 11;
      print(map8);//{a: 11, b: 2, c: 3, d: 4, e: 5}
    • update () to make changes in the value of the specified key
      Map <String, int > map23 = { "A":. 1, "B": 2, "C":. 3 };
        int result3 map23.update = ( "A", (value) => (2 * value)) ; // Key parameters of the function to modify its present value in accordance with 
       Print (result3); // 2 
       Print (map23); // {A: 2, B: 2, C:. 3}
      int result4 map23.update = ( "D", (value) => (2 * value)); // Key given the absence 
       int result4 map23.update = ( "D", (value) => (2 * value) , ifAbsent: () => (10)); // Key does not exist but ifAbsent Arguments return value ifAbsent function and added to the map 
       Print (result4); // 10 
       Print (map23); // {a: 2 , b: 2, c: 3 , d: 10}

       

    • updateAll () function of the parameters according to the rules, bulk edit map

          Map<String,int> map24 = {"a":1,"b":2,"c":3};
          map24.updateAll((String key,int value){
            return value*2;
          });//
          print(map24);//{a: 2, b: 4, c: 6}
          
          Map<String,int> map25 = {"a":1,"b":2,"c":3};
          map25.updateAll((String key,int value){
            if(key=="a"){return 10;}
            if(key=="b"){return 20;}
            return value*2;
          });//
          print(map25);//{a: 10, b: 20, c: 6}
  • delete
    • remove () to delete a key
          Map<String,int> map9 = {"a":1,"b":2,"c":3,"d":4,"e":5};
          map9.remove("b");
          print(map9);//{a: 11, c: 3, d: 4, e: 5}

       

    • removeWhere () delete batch depending on conditions

      Map <String, int > MAP10 = { "A":. 1, "B": 2, "C":. 3, "D":. 4, "E":. 5 }; 
      map10.removeWhere ((Key, value) = > (value>. 3)); // delete the function of the parameters meet keyvalue 
      Print (MAP10); // {a:. 1, B: 2, C:. 3}
    • containsKey () contains the key  
         Map<String,int> map11 = {"a":1,"b":2,"c":3,"d":4,"e":5};
         print(map11.containsKey("a"));//true   是否包含key
         print(map11.containsKey("aa"));//false  是否包含key
    • containsValue () value contains a value
         Map<String,int> map17 = {"a":1,"b":2,"c":3};
         print(map17.containsValue(1));//true
         print(map17.containsValue(4));//false
    • forEach () traversal
          Map<String,int> map12 = {"a":1,"b":2,"c":3,"d":4,"e":5};
          map12.forEach((String key,int value){
           print("$key  $value");
            a  1
            b  2
            c  3
            d  4
            e  5
          });
    • 遍历时修改value值
          Map<String,int> map13 = {"a":1,"b":2,"c":3};
          map13.forEach((String key,int value){
          print("$key  $value");
          map13["c"] = 4;
            a  1
            b  2
            c  4
          });

      note:

      遍历时,新增或删除key  都会报错
          Map<String,int> map14 = {"a":1,"b":2,"c":3};
          map14.forEach((String key,int value){
            print("$key  $value");
            map14["d"] = 4;//  报错
            map14.remove("a");//  报错
          });
  • other
    • map () function according to the parameters through each element, to make changes keyvalue, may be converted to other generic Map
        Map<String,int> map19 = {"a":1,"b":2,"c":3};
          Map<int,String> map20 = map19.map((String key,int value){
            return new MapEntry(value, key);
          });
         print(map20);//{1: a, 2: b, 3: c}
    • clear () Clear map
         Map<String,int> map15 = {"a":1,"b":2,"c":3};
         map15.clear();
         print(map15);//{}
    • addAll () overall another merger to be consistent generic map
         The Map <String, int > map16 = { "A":. 1, "B": 2, "C":. 3 }; 
         map <String, int > OTHER = { "A":. 1, "C":. 4, " D ":. 7 }; 
         map16.addAll (OTHER); // Key values are the same value latter over the former, then add in the absence of the former case 
         Print (map16); // {A:. 1, B: 2, C: 4, d: 7}
    • addEntries () merge two duplicate if the key map, the map value to be merged over the former
          Map<String,int> map26 = {"a":1,"b":2,"c":3};
          Map<String,int> map27 = {"a":1,"b":4,"d":3,"e":5};
          map26.addEntries(map27.entries);
          print(map26);//{a: 1, b: 4, c: 3, d: 3, e: 5}
    • the putIfAbsent () key to obtain the present value does not exist and returns the value added to the map
          Map <String, int > map18 = { "A":. 1, "B": 2, "C":. 3 };
           int Result = map18.putIfAbsent ( "A", () => (2)); // presence 
          Print (Result); // value of the acquired key. 1 
          Print (map18); // {a:. 1, B: 2, C: Map unchanged. 3} 
          int result2 map18.putIfAbsent = ( "D", () = > (2)); // absent 
          Print (result2); // 2 to obtain a new key value 
          Print (map18); // {a:. 1, B: 2, C:. 3, D: 2} Map change
    • cast () to enhance its generic type class leaves his father
          Map<String,int> map21 = {"a":1,"b":2,"c":3};
          Map<Object,Object> map22 = map21.cast();
          map22["d"]=33;
          print(map22);//{a: 1, b: 2, c: 3, d: 33}
  • General Method

    List, Set, and Map are some common methods. Some of these methods are derived from common class Iterable. List and Set realize iterable class.

    Although the Map does not implement Iterable, but Map of property keys and values ​​are Iterable object.

    • IsEmpty common attributes and isNotEmpty

      var testSet = Set.from(["a", "b", "c"]);
      var testList = [1, 2, 3, 4];
      var testMap = Map();
      
      print(testSet.isNotEmpty); // true
      print(testList.isEmpty); // false
      print(testMap.isEmpty); // true
      
      testMap.addAll({
      "zh": "china",
      "us": "usa"
      });
    • forEach method

      testList.forEach((num) => print("I am num ${num}")); // I am num 1 等等
      testMap.forEach((k, v) => print("${k} is ${v}")); // zh is china 等等
    • iterable map provides a method to deal with each of a set of objects, and returns a result

      var setIter = testSet.map((v) => v.toUpperCase());
      print(setIter); // (A, B, C)
    • It may result into a list or collection toList and toSet

      var listIter = testSet.map((v) => v.toUpperCase()).toList();
      print(listIter); // [A, B, C]
    • iterable provides a method where, to filter the set of values, and returns a collection

      testList.where whereList = var ((NUM) => NUM> 2 ) .ToList (); 
      Print (whereList); // [. 3,. 4]. If you do not toList () returns (3, 4)
    • iterable provided any method and every method to determine whether the value set in the condition and return bool

      print(testList.any((num) => num > 2)); // true

V. Summary

  1. When the Key Map not specify a type, Key type not inconsistent error.
  2. Map inside the key can not be the same. But may be the same value, value can be an empty string or null.
  3. Map created in two ways: by the constructors (new) and direct assignment.

  

 

 

Guess you like

Origin www.cnblogs.com/lxlx1798/p/11122881.html