Home > Net >  dart/flutter update keys of map
dart/flutter update keys of map

Time:10-21

I want to update the keys of a map. I sorted the map by date, but now the keys are not in numerical order

original Map:

Map<dynamic, dynamic> myMap = {
    0: {"id": 754, "name": "luke", "date": 1665537500000},
    1: {"id": 436, "name": "obi", "date": 1665532400000},
    2: {"id": 866, "name": "vader", "date": 1665532500000},
  };

myMapSorted = SplayTreeMap.from(myMap, (a, b) => myMap[a]['time'].compareTo(myMap[b]['time']));
print(myMapSorted);

sorted Map (with keys in not numerical order):

{
    1: {"id": 436, "name": "obi", "date":  1665532400000},
    2: {"id": 866, "name": "vader", "date": 1665532500000},
    0: {"id": 754, "name": "luke", "date": 1665537500000}, 
  };

is there a way to update the keys?

CodePudding user response:

As mentioned by Ουιλιαμ Αρκευα, the second method of article solves your issue of sorting by keys.

var sortMapByKey = Map.fromEntries(
    myMap.entries.toList()
    ..sort((e1, e2) => e1.key.compareTo(e2.key)));
    
  print("***Sorted Map by key***");
  print(sortMapByKey);

CodePudding user response:

If you find yourself using a Map with integer keys that are contiguous and where you don't care about insertion order, you should step back and ask yourself if you should be using a List instead, especially if your keys also start from 0. Using a List is simpler and more efficient.

It sounds like that applies to your situation. Instead of:

Map<dynamic, dynamic> myMap = {
    0: {"id": 754, "name": "luke", "date": 1665537500000},
    1: {"id": 436, "name": "obi", "date": 1665532400000},
    2: {"id": 866, "name": "vader", "date": 1665532500000},
  };

use:

var myMap = <dynamic>[
    {"id": 754, "name": "luke", "date": 1665537500000},
    {"id": 436, "name": "obi", "date": 1665532400000},
    {"id": 866, "name": "vader", "date": 1665532500000},
];

and then you can sort it directly with:

myMap.sort((a, b) => a['date'].compareTo(b['date']));

to obtain:

[
  {'id': 436, 'name': 'obi', 'date': 1665532400000},
  {'id': 866, 'name': 'vader', 'date': 1665532500000},
  {'id': 754, 'name': 'luke', 'date': 1665537500000},
]

And now you don't need to worry about updating any Map keys since they are implicitly the indices of the List elements.

  • Related