52

I have question in sorting Map's key in Dart.

Map<String, Object> map = new Map();

How can I sort the keys in map? or Sort the Iterable map.keys.

K Walrath
  • 300
  • 3
  • 10
Roger Chan
  • 1,293
  • 2
  • 11
  • 24

6 Answers6

92

In Dart, it's called SplayTreeMap:

import "dart:collection";

main() {
  final SplayTreeMap<String, Map<String,String>> st = 
      SplayTreeMap<String, Map<String,String>>();

  st["yyy"] = {"should be" : "3rd"};
  st["zzz"] = {"should be" : "last"};
  st["aaa"] = {"should be" : "first"};
  st["bbb"] = {"should be" : "2nd"};

  for (final String key in st.keys) {
    print("$key : ${st[key]}");
  }
}

// Output:
// aaa : first
// bbb : 2nd
// yyy : 3rd
// zzz : last
Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
Ilya Kharlamov
  • 3,698
  • 1
  • 31
  • 33
54

If you want a sorted List of the map's keys:

var sortedKeys = map.keys.toList()..sort();

You can optionally pass a custom sort function to the List.sort method.

Finally, might I suggest using Map<String, dynamic> rather than Map<String, Object>?

Ganymede
  • 3,345
  • 1
  • 22
  • 17
  • 10
    Watch out for one-liner `map.keys.toList().sort()`. In order to keep this in the same line, the cascade style should be used, as in `map.keys.toList()..sort()`. – nunobaba Dec 08 '13 at 20:23
8
final sorted = SplayTreeMap<String,dynamic>.from(map, (a, b) => a.compareTo(b));

As seen at

How to use a SplayTreeMap on Firebase snapshot dictionary in dart/Flutter?

BananaMaster
  • 377
  • 6
  • 15
6

I know my answer is too late but check out what I've found.. Might help someone

This sortedmap Package helps to maintain Map of objects in a sorted manner.

Jerin
  • 688
  • 1
  • 9
  • 21
1
map.entries.toList().sort(((a, b) => a.key.compareTo(b.key)));

I think so.

Zero
  • 2,764
  • 1
  • 17
  • 20
0

I suggest the following code:

void main() {
  var x = {'b': 10, 'c': 7, 'a': 2};
  print('x = $x');
  
  final  y = x.orderByKeys(compareTo: (a, b) => a.compareTo(b));
  final  z = x.orderByValues(compareTo: (a, b) => a.compareTo(b));
  print('y = $y');
  print('z = $z');
  
  
}

/// Extensions on [Map] of <[K], [V]>
extension ExtendsionsOnMapDynamicDynamic<K,V> on Map<K, V>{
  /// Order by keys
  Map<K, V> orderByKeys({required int Function(K a, K b) compareTo}) {
    return Map.fromEntries(entries.toList()..sort((a, b) => compareTo(a.key, b.key)));
  }

  /// Order by values
  Map<K, V> orderByValues({required int Function(V a, V b) compareTo}) {
    return Map.fromEntries(entries.toList()..sort((a, b) => compareTo(a.value, b.value)));
  }
}
Vahid Rajabi
  • 191
  • 3
  • 3
iMe Tonya
  • 51
  • 2