乐闻世界logo
搜索文章和话题

How to Sort Keys in a Map in Dart

2月7日 11:32

In Dart, if you want to sort the keys of a Map, you can extract the keys into a list, sort the list, and then reconstruct a new Map based on the sorted key list. Here is a step-by-step guide with an example code:

Extract Keys and Sort: Extract all keys into a list and sort it using the List.sort method.

Reconstruct the Map Based on Sorted Keys: Create a new Map and populate it with values from the original Map based on the sorted key list.

Here is a concrete example:

dart
void main() { Map<String, int> unsortedMap = { 'banana': 3, 'apple': 1, 'orange': 2 }; // Extract keys into a list var keys = unsortedMap.keys.toList(); // Sort the key list keys.sort(); // Create a new Map and populate it based on the sorted key list Map<String, int> sortedMap = { for (var key in keys) key: unsortedMap[key] }; print(sortedMap); // Output: {apple: 1, banana: 3, orange: 2} }

This approach is suitable for scenarios requiring lexicographical or custom sorting of keys. For other types of sorting (e.g., numerical order), you can provide a custom comparison function in the sort method.

标签:Dart