我有以下地图
Map testMap = {
3 : {
'order': 3,
'sample' : 'sample'
},
2 : {
'order': 2,
'sample' : 'sample'
},
1 : {
'order': 1,
'sample' : 'sample'
},
4: {
'order': 4,
'sample' : 'sample'
}
};
我如何按键对其进行排序,如果订单不可能按顺序排序'子图中的值。
注意:地图最多可增加100个字段。
解决
我以前一定很累,但以防其他人在这里寻找是我的解决方案。另外,用SplayTreeMap
按键排序会产生一个奇怪的顺序,如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);
}
答案 0 :(得分:1)
import 'package:queries/collections.dart';
void main() {
var d = Dictionary.fromMap(testMap);
// Sort by key
var q = d
.orderBy((kv) => kv.key)
.toDictionary$1((kv) => kv.key, (kv) => kv.value);
print(q.toMap());
// Sort by the value 'order' in reverse order
q = d
.orderByDescending((kv) => int.parse(kv.value['order']))
.toDictionary$1((kv) => kv.key, (kv) => kv.value);
print(q.toMap());
}
var 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'}
};
结果:
{1: {order: 1, sample: sample}, 2: {order: 2, sample: sample}, 3: {order: 3, sample: sample}, 4: {order: 4, sample: sample}, 11: {order: 11, sample: sample}, 21: {order: 21, sample: sample}, 31: {order: 31, sample: sample}}
{31: {order: 31, sample: sample}, 21: {order: 21, sample: sample}, 11: {order: 11, sample: sample}, 4: {order: 4, sample: sample}, 3: {order: 3, sample: sample}, 2: {order: 2, sample: sample}, 1: {order: 1, sample: sample}}
答案 1 :(得分:1)
有关根据其值对Map进行排序的示例代码
vector<std::unique_ptr<Foo>> my_vector;
void setFoo(Foo foo) {
my_vector.emplace_back(std::make_unique<Foo>(foo));
}