To sort a map by keys in Dart, you can use the `SplayTreeMap` from the `dart:collection` library, which automatically sorts the keys. Alternatively, you can convert the map to a list of key-value pairs, sort the list, and then convert it back to a map.
We can sort a map by keys in Dart using the `SplayTreeMap`, which automatically sorts the keys.
For example,
originalMap
with some key-value pairs. In this example, the map has integer keys and string values.sortedMap
and pass the `originalMap` to it, which automatically sorts the keys.print
function to verify the sorting.import 'dart:collection';
void main() {
// Declare and initialize a map
Map<int, String> originalMap = {
3: 'three',
1: 'one',
2: 'two'
};
// Create a SplayTreeMap to sort the keys
SplayTreeMap<int, String> sortedMap = SplayTreeMap.from(originalMap);
// Print the sorted map
print('Sorted Map by Keys:');
sortedMap.forEach((key, value) => print('$key: $value'));
}
Sorted Map by Keys: 1: one 2: two 3: three
We can sort a map by keys in Dart by converting the map to a list of key-value pairs, sorting the list, and then converting it back to a map.
For example,
originalMap
with some key-value pairs. In this example, the map has integer keys and string values.print
function to verify the sorting.void main() {
// Declare and initialize a map
Map<int, String> originalMap = {
3: 'three',
1: 'one',
2: 'two'
};
// Convert the map to a list of key-value pairs and sort the list by keys
var sortedEntries = originalMap.entries.toList()
..sort((a, b) => a.key.compareTo(b.key));
// Create a new map from the sorted list of key-value pairs
Map<int, String> sortedMap = {
for (var entry in sortedEntries) entry.key: entry.value
};
// Print the sorted map
print('Sorted Map by Keys:');
sortedMap.forEach((key, value) => print('$key: $value'));
}
Sorted Map by Keys: 1: one 2: two 3: three
We can sort a map by keys in descending order in Dart using the `SplayTreeMap` with a custom comparator.
For example,
originalMap
with some key-value pairs. In this example, the map has integer keys and string values.sortedMap
with a custom comparator to sort the keys in descending order, and pass the `originalMap` to it.print
function to verify the sorting.import 'dart:collection';
void main() {
// Declare and initialize a map
Map<int, String> originalMap = {
3: 'three',
1: 'one',
2: 'two'
};
// Create a SplayTreeMap with a custom comparator for descending order
SplayTreeMap<int, String> sortedMap = SplayTreeMap<int, String>((a, b) => b.compareTo(a))
..addAll(originalMap);
// Print the sorted map
print('Sorted Map by Keys (Descending):');
sortedMap.forEach((key, value) => print('$key: $value'));
}
Sorted Map by Keys (Descending): 3: three 2: two 1: one
In this tutorial, we learned How to Sort a Map by Keys in Dart language with well detailed examples.