'Dart - How to sort Map's 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.
Solution 1:[1]
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>
?
Solution 2:[2]
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
Solution 3:[3]
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.
Solution 4:[4]
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?
Solution 5:[5]
map.entries.toList().sort(((a, b) => a.key.compareTo(b.key)));
I think so.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Philippe Fanaro |
Solution 3 | Jerin |
Solution 4 | BananaMaster |
Solution 5 | Zero |