Dart:按其值对地图的条目进行排序
想象一下你的老板给了你一张这样的 Dart 地图:
final Map<String, int> myMap = {
'a': 10,
'b': 20,
'c': 15,
'd': 5,
'e': 14
};
然后他要求您按地图值的升序/降序对地图进行排序。你如何解决这个问题并让他开心?好吧,解决方案很简单。让我们看看下面的两个例子。
按值的升序对地图进行排序
编码:
// KindaCode.com
void main() {
final Map<String, int> myMap = {'a': 10, 'b': 20, 'c': 15, 'd': 5, 'e': 14};
// sort the map in the ascending order of values
// turn the map into a list of entries
List<MapEntry<String, int>> mapEntries = myMap.entries.toList();
// sort the list
mapEntries.sort((a, b) => a.value.compareTo(b.value));
// turn the list back into a map
final Map<String, int> sortedMapAsc = Map.fromEntries(mapEntries);
// print the result
print(sortedMapAsc);
}
输出:
{d: 5, a: 10, e: 14, c: 15, b: 20}
按值的降序对地图进行排序
代码与前面的示例几乎相同,只是我们更改了这一行:
mapEntries.sort((a, b) => a.value.compareTo(b.value));
对此:
mapEntries.sort((a, b) => b.value.compareTo(a.value));
这是完整的代码:
// KindaCode.com
void main() {
final Map<String, int> myMap = {'a': 10, 'b': 20, 'c': 15, 'd': 5, 'e': 14};
// sort the map in the ascending order of values
// turn the map into a list of entries
List<MapEntry<String, int>> mapEntries = myMap.entries.toList();
// sort the list in descending order of values
mapEntries.sort((a, b) => b.value.compareTo(a.value));
// turn the list back into a map
final Map<String, int> sortedMapAsc = Map.fromEntries(mapEntries);
// print the result
print(sortedMapAsc);
}
输出:
{b: 20, c: 15, e: 14, a: 10, d: 5}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。