Home > Software engineering >  Dart sort a map containing both numeric and alpha keys in descending order
Dart sort a map containing both numeric and alpha keys in descending order

Time:01-11

I have the following map

Map<String, String> Dictionary = {
    '37': 'thirty-four',
    '94': 'ninety',
    '91': 'ninety-one',
    '22': 'twenty-one',
    '61': 'sixty-one',
    '9': 'nine',
    '3': 'three',
    '8': 'eight',
    '80': 'eighty',
    '81': 'eighty-one',
    'Ninety-eight': '98',
    'nine-hundred': '900'};

I'd like to sort it in ascending order such that the final result is

3: three
8: eight
9: nine
22: twenty-two
37: thirty-seven
61: sixty-one
80: eighty
81: eighty-one
91: ninety-one
94: ninety four
Ninety-eight': 98
nine-hundred': 900

However the result I'm getting is

22: twenty-two
3: three
37: thirty-seven
61: sixty-one
8: eight
80: eighty
81: eighty-one
9: nine
91: ninety-one
94: ninety-four
Ninety-eight: 98
nine-hundred: 900

My code for the above results is as follows

sortDict(){

    var sortedByKeyMap = Map.fromEntries(
        Dictionary.entries.toList()..sort((e1, e2) => (e1.key).compareTo((e2.key))));

    print(sortedByKeyMap);


  }

Any idea on how to convert the numeric string keys to int first?

CodePudding user response:

A small trick would help you,

   var sortedByKeyMap = Map.fromEntries(
        Dictionary.entries.toList()
     ..sort((e1,e2) {
       if(int.tryParse(e1.key)!=null && int.tryParse(e2.key)!=null)
       {
         return int.parse(e1.key).compareTo(int.parse(e2.key));
       }
       else
       {
          return -1; 
       }
     })); 
     
    print(sortedByKeyMap);

output:

{
   "3":"three",
   "8":"eight",
   "9":"nine",
   "22":"twenty-one",
   "37":"thirty-four",
   "61":"sixty-one",
   "80":"eighty",
   "81":"eighty-one",
   "91":"ninety-one",
   "94":"ninety",
   "Ninety-eight":98,
   "nine-hundred":900
}
  • Related