'Sort maps in Dart by key or by value
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);
}
Solution 1:[1]
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);
}
Solution 2:[2]
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | theredcap |
Solution 2 |