Home > Blockchain >  How to get the length for each list according to its key inside map
How to get the length for each list according to its key inside map

Time:01-21

how to get the length for each list according to its key
Map mymap= <String, List>;

Example key1 : 5(length of the value(list)) key2 : 48

CodePudding user response:

It seems similar to this,

you can do mymap['k1']?.length, here ?. means it will return null if there is no value.

Rest you can follow @zabaykal's answer.

 Map<String, List> mymap = {
    "k1": [1, 2, 4],
    "k2": [5, 6, 7],
    "k3": []
  };

  print(mymap['k1']?.length);

  mymap.forEach((key, value) {
    print('$key: ${value.length}');
  });

CodePudding user response:

If you want to create a second map with the original keys and the respective lengths as the value you can use the following code where initialMap is the original map with List<T> as values:

final mapListCount = initialMap.map((key, value) => MapEntry(key, value?.length));
  •  Tags:  
  • Related