Daniel
Daniel

Reputation: 486

How can I store data into map<String, List<String>> using Dart?

I have the bellow data structure

Map<String, List<String>> description = {};

And this data:

 Key       value
....       .....
 car        bmw
 car        bmw
computer    acer
computer    asus
computer    ibm 
...

I want to store data as bellow shows, how can I achieve with Dart

 "car"      : ["toyota", "bmw", "honda"]
 "fruit"    : ["apple","banana"]
 "computer" : ["acer","asus","ibm"]

Upvotes: 0

Views: 128

Answers (1)

AmazingBite
AmazingBite

Reputation: 312

You could do something like that.

Map<String, List<String>> description = Map<String, List<String>>();

description['computer'] = ['acer', 'asus', 'ibm'];

description['car'] = List<String>();
description['car'].add('toyota');
description['car'].add('mercedes');

If you want to automate, you could do loop. Don't forget to check if the key exist and create it if not. (Edit thanks to @julemand101)

description.putIfAbsent(key, () => List<String>());

Upvotes: 2

Related Questions