Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
In Dart programming, the List data type is similar to arrays in other programming languages. Lists are used to represent collections of objects. It’s an ordered set of objects. The core library in Dart is responsible for the existence, creation, and manipulation of the List class. The sorting of the list depends on the type of list we are sorting, that is, if we are sorting a list of integers we can use a simple sorting function, whereas if it is a list of strings we use compareTo to sort the list.
Sort a list of integers
Lists of integers can be sorted by a simple sort function.
Example: Sort a list of integers.
// Main function
main() {
// Creating List
List<int> geeksforgeeks = [13, 2, -11, 142, -389, 32, 3032, 0];
// Sorting List
geeksforgeeks.sort();
// Printing Sorted List
print(geeksforgeeks);
}
Copy the code
Sort a list of strings
Sort strings by comparing lengths in the sort function.
Example: Sort a list of strings.
// Main function
main() {
// Creating list of string
List<String> geeksforgeeks = ['one', 'two', 'three', 'four'];
// Sorting string by comparing the length
geeksforgeeks.sort((a, b) => a.length.compareTo(b.length));
// Printing the list
print(geeksforgeeks);
}
Copy the code
If we use sort without comparing lengths, then:
Example: Sort a list of strings without comparing lengths.
// Main function
main() {
// Creating list of string
List<String> geeksforgeeks = ['one', 'two', 'three', 'four'];
// Sorting string without
// comparing the length
geeksforgeeks.sort();
// Printing the list
print(geeksforgeeks);
}
Copy the code
Example: Using the cascading method when sorting a list.
// Main function main() { // Creating list of string List<int> geeksforgeeks = [13, 2, -11, 142, -389, 0]; // Sorting string and Printing the list print(geeksforgeeks.. sort()); }Copy the code
1