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.
To sort a Map , we can utilize the SplayTreeMap . Sorted keys are used to sort the SplayTreeMap . A SplayTreeMap is a type of map that iterates keys in a sorted order.
5. map is used to store elements as key,value pairs in sorted order. unordered_map is used to store elements as key,value pairs in non-sorted order.
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>
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With