Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Map<key, value> to List<value>

I've been searching for a while without success. I am trying to convert a Map to a List (discarding key).

Sure, I can do

var addictionList = new List<AddictionDay>();
dataMan.forEach((String date, AddictionDay day) {
    addictionList.add(day);
});

but is there a more straight approach, like

var addictionList = dataMan.toList(); 

?

map function of Map doesn't seem to help a lot, because it accepts only MapEntry<K2, V2> as a param so it's a no go. Pretty surprised nobody asked this question before.

I was also thinking about new class extending Map, but right now I am just looking into some native way to do this, if it exists.

like image 377
Martin. Avatar asked Mar 17 '19 21:03

Martin.


2 Answers

Map class has the entries property which returns the map entries as an iterable on which you can use the map function to generate the list of items you need.

var addictionList = dataMan.entries.map((MapEntry mapEntry) => mapEntry.value).toList();

mapEntry.key is the type of String and mapEntry.value is the type of AddictionDay.

like image 87
Anis Alibegić Avatar answered Oct 18 '22 15:10

Anis Alibegić


Do you need this or something more complicated?

  var _map = {1: 'one', 2: 'two', 3: 'three'};
  var values =_map.values.toList();
  print(values);

Result:

[one, two, three]

like image 42
mezoni Avatar answered Oct 18 '22 15:10

mezoni