Dart - How to sort Map's keys

2019-02-21 16:47发布

问题:

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.

回答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>?



回答2:

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


回答3:

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.



标签: dart