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.
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>
?
In Dart It's called SplayTreeMap:
import "dart:collection";
main() {
var st = new SplayTreeMap<String, Object>();
st["yyy"]={"should be":"3rd"};
st["zzz"]={"should be":"last"};
st["aaa"]={"should be":"first"};
st["bbb"]={"should be":"2nd"};
for (var key in st.keys) {
print("$key : ${st[key]['should be']}");
}
}
//Output:
//aaa : first
//bbb : 2nd
//yyy : 3rd
//zzz : last
Use a TreeMap
. That should solve your issue.
Map<String, String> unsortMap = new HashMap<String, String>();
unsortMap.put("2", "B");
unsortMap.put("1", "A");
unsortMap.put("4", "D");
unsortMap.put("3", "B");
Map<String, String> treeMap = new TreeMap<String, String>(unsortMap);
Hope this helps.