Reputation: 3248
I have the following map
Map testMap = {
3 : {
'order': 3,
'sample' : 'sample'
},
2 : {
'order': 2,
'sample' : 'sample'
},
1 : {
'order': 1,
'sample' : 'sample'
},
4: {
'order': 4,
'sample' : 'sample'
}
};
How i can sort it by key, if not possible by the 'order' value inside child map.
Note: the Map grows up to 100 fields.
SOLVED
i must have been tired before, but just in case someone else is looking here is my solution. Also, ordering just by key with SplayTreeMap
produce a strange order like this 1,10,11,12,13,14,15,16,17,18,19,2,20,21 ...
import 'dart:collection';
void main() {
Map testMap = {
11: {
'order': '11',
'sample' : 'sample'
},
3 : {
'order': '3',
'sample' : 'sample'
},
2 : {
'order': '2',
'sample' : 'sample'
},
1 : {
'order': '1',
'sample' : 'sample'
},
4: {
'order': '4',
'sample' : 'sample'
},
31: {
'order': '31',
'sample' : 'sample'
},
21: {
'order': '21',
'sample' : 'sample'
}
};
final sorted = new SplayTreeMap.from(testMap, (a, b) => int.parse(testMap[a]['order']).compareTo(int.parse(testMap[b]['order'])));
print(sorted);
}
Upvotes: 10
Views: 10188
Reputation: 1622
This is the easiest way for sorting maps by keys in dart.
var map = {
"a": 1,
"c": 3,
"b": 2,
};
void main() {
final sorted = Map.fromEntries(map.entries.toList()..sort((e1, e2) => e1.key.compareTo(e2.key)));
print(sorted);
}
Upvotes: 8
Reputation: 692
A sample code on sorting Map based on it's value
import 'dart:collection';
var map = {
"a": 2,
"b": 1,
"c": -1,
};
void main() {
final sorted = new SplayTreeMap<String,dynamic>.from(map, (a, b) => map[a] > map[b] ? 1 : -1 );
print(sorted);
}
Upvotes: 5