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
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:Note that
lastBy
is implemented there as a simple one-liner using a map comprehension.It’s easier to use Map.fromIterable():
Or equivalently with a Map literal:
This differs from your snippet in that if there are duplicate keys, the last value is kept (your code keeps the first value).