Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart - How to sort Map's keys

Tags:

dart

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.

like image 864
Roger Chan Avatar asked Aug 15 '13 00:08

Roger Chan


People also ask

How do you sort a dart map by key?

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.

Does map store keys in 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.


2 Answers

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 
like image 143
Ilya Kharlamov Avatar answered Oct 01 '22 11:10

Ilya Kharlamov


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

like image 24
Ganymede Avatar answered Oct 01 '22 11:10

Ganymede