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.
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.
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
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>
?
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?
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)));
}
}