import 'dart:collection';
void main() {
Map<String, int> mydata = {
'a': 100,
'b': 90,
'c': 120,
'd': 110,
'e': 300,
'f': 90,
};
//value值排序
List<int> sortedvalues = mydata.values.toList();
sortedvalues.sort((a, b) {
return b - a;
});
print(sortedvalues);
//key值排序
List<String> sortedkeys = mydata.keys.toList();
sortedkeys.sort((a, b) {
return a.compareTo(b);
});
print(sortedkeys);
//利用list的sort方法將map方法排序
//map轉成list
List<MapEntry<String, int>> mydatalist = mydata.entries.toList();
//利用list的sort方法排序,可以利用a.key 或是a.value決定排序key或是value
mydatalist.sort(((a, b) {
//return b.value - a.value; //降序
//return a.value - b.value; //升序
return a.key.compareTo(b.key);
}));
//轉回來list
Map<String, int> new_sorteddata = Map.fromEntries(mydatalist);
print(new_sorteddata);
//利用SplayTreeMap方法排序,下面調整k1或是 mydata[k1],可以改變是要依key值,還是value值排序
var sortedBykeyMap = new SplayTreeMap<String, int>.from(
mydata, (k1, k2) => k1.toString().compareTo(k2.toString()));
print(sortedBykeyMap);
var sortedByvalueMap = new SplayTreeMap<String, int>.from(mydata,
(k1, k2) => mydata[k1].toString().compareTo(mydata[k2].toString()));
print(sortedByvalueMap);
}
沒有留言:
張貼留言