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

How to sort Map's keys in Dart

1个答案

1

In Dart, a Map is an unordered collection where the keys and values have no specific order.

If you want to sort a Map by its keys, you can convert the Map's keys into a list, sort the list, and then reconstruct a new Map based on the sorted list.

Here is a concrete example demonstrating how to sort a Map by its keys:

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

In this example, we first create a Map containing fruits and their corresponding quantities. Then we use .keys to retrieve all keys and convert them to a list. We apply the sort() method to order the keys. Finally, we use Dart's collection literals (specifically map literals) with a for loop to construct a new Map from the sorted keys.

The output will be:

shell
{apple: 1, banana: 3, orange: 2}

This Map is sorted alphabetically by key.

This approach works for any key type as long as the keys are sortable. If your keys are custom objects, you may need to provide a comparison function to the sort() method to ensure correct ordering.

2024年7月18日 20:14 回复

你的答案