如何排序地图值? [英] How to sort map value?
本文介绍了如何排序地图值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这张地图:
var temp= {
'A' : 3,
'B' : 1,
'C' : 2
};
如何对地图的值进行排序(降序)。我知道,我可以使用temp.values.toList().. sort()。
How to sort the values of the map (descending). I know, I can use temp.values.toList()..sort().
但我想在这样的键的上下文中排序:
But I want to sort in context of the keys like this:
var temp= {
'B' : 1,
'C' : 2
'A' : 3,
};
推荐答案
此示例使用自定义比较函数, c $ c> sort()按值对键排序。然后,键和值被插入到 LinkedHashMap
中,因为这种类型的映射保证了保持顺序。
基本上与 http://stackoverflow.com/a/29629447/217408 相同,但根据您的使用进行了自定义
This example uses a custom compare function which makes sort()
sort the keys by value. Then the keys and values are inserted into a LinkedHashMap
because this kind of map guarantees to preserve the order.
Basically the same as http://stackoverflow.com/a/29629447/217408 but customized to your use case.
import 'dart:collection';
void main() {
var temp= {
'A' : 3,
'B' : 1,
'C' : 2
};
var sortedKeys = temp.keys.toList(growable:false)
..sort((k1, k2) => temp[k1].compareTo(temp[k2]));
LinkedHashMap sortedMap = new LinkedHashMap
.fromIterable(sortedKeys, key: (k) => k, value: (k) => temp[k]);
print(sortedMap);
}
尝试 DartPad
这篇关于如何排序地图值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文