skip to Main Content

I have a list of maps, the problem is that if I want find some map which contains some specyfic "value" (that value is unique in whole list of maps) I need to iterate over the whole List (looking for that specyfic value in every map, maybe that value is in the first map, but maybe it’s in the last) so I want to convert that list into map of maps for obvious reason,

so the question is what is the most efficient way to convert list of maps into map of maps with keys of new map being created from some value of old elements of maps from that list?

*the map itself doents need to be changed

example

void main() {
  List<Map> listOfMaps =[{'type': 'human','name':'person'}, {'type':'animal','name':'dog'}, {'type':'furniture','name':'table'}];
  Map<String,Map> mapOfMaps = {};
  
  for (Map element in listOfMaps){
   mapOfMaps.putIfAbsent(element['type'], () => element); 
  }
  print("listOfMaps -> ${listOfMaps}");
  print("mapOfMaps -> ${mapOfMaps}");
}

output

listOfMaps -> [{type: human, name: person}, {type: animal, name: dog}, {type: furniture, name: table}]
mapOfMaps -> {human: {type: human, name: person}, animal: {type: animal, name: dog}, furniture: {type: furniture, name: table}}

Is it the best way or dart has some better mechanism to do that process?

2

Answers


  1. If the speed is critical, it might make sense to look into storing the initial listOfMaps differently, e.g. with some index updated on every insert/update.

    Short of that, the code can be a little shorter (and possibly faster) by using the collection library:

    void main() {
      List<Map> listOfMaps = [
        {'type': 'human', 'name': 'person'},
        {'type': 'animal', 'name': 'dog'},
        {'type': 'furniture', 'name': 'table'}
      ];
    
      Map<String, Map> mapOfMaps = lastBy(listOfMaps, (m) => m["type"]);
    
      print("listOfMaps -> ${listOfMaps}");
      print("mapOfMaps -> ${mapOfMaps}");
    }
    

    Note that lastBy is implemented there as a simple one-liner using a map comprehension.

    Login or Signup to reply.
  2. It’s easier to use Map.fromIterable():

    Map<String, Map> mapOfMaps = Map.fromIterable(listOfMaps, key: (m) => m['type']);
    

    Or equivalently with a Map literal:

    Map<String, Map> mapsByType = {for (var m in listOfMaps) m['type']: m};
    

    This differs from your snippet in that if there are duplicate keys, the last value is kept (your code keeps the first value).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search