Reputation: 5768
I'm trying to convert the following map into 2 lists.
Map map = {'Jack': 'red', 'Adam': 'blue', 'Katherin': 'green'};
I would like to become this: (the order is important)
List myList1 = ['Jack', 'Adam', 'Katherin'];
List myList2 = ['red', 'blue', 'green'];
Is this possible and how can it be done? I searched trough stack overflow and the responses gave me this list (what's not what I'm searching for)
[{ Jack, 'red' }, { Adam, 'blue' }, { Katherin, 'green' }] // not what I need
Thanks for the help and effort!
Upvotes: 1
Views: 1700
Reputation: 2352
If I get the question right, what you are looking for is already build into Map Class. take a look:
Map map = {'Jack': 'red', 'Adam': 'blue', 'Katherin': 'green'};
print(map.keys.toList());
print(map.values.toList());
Output:
[Jack, Adam, Katherin]
[red, blue, green]
I hope it is what you are looking for.
Upvotes: 2
Reputation: 123
Simply fill your map and use the keys and values iterable getters to form a list.
void main() {
Map<String, String> map = Map<String, String>();
map["Jack"] = "red";
map["Adam"] = "blue";
map["Katherin"] = "green";
print(map.toString());
List<String> names = map.keys.toList();
List<String> colors = map.values.toList();
print(names);
print(colors);
}
Output
{Jack: red, Adam: blue, Katherin: green}
[Jack, Adam, Katherin]
[red, blue, green]
Upvotes: 1
Reputation: 80904
To be able to do that you can do the following:
Map map = {'Jack': 'red', 'Adam': 'blue', 'Katherin': 'green'};
List<String> values = List();
List<String> keys = List();
map.forEach((k,v) => values.add(v));
print(values);
map.forEach((k,v) => keys.add(k));
print(keys);
Use forEach
to iterate inside the values of the map, then use the add()
method to add the key
to one list and the values
to another list.
Upvotes: 1