In Dart programming, the List data type is similar to arrays in other programming languages. A list is used to represent a collection of objects. It is an ordered group of objects. The core libraries in Dart are responsible for the existence of List class, its creation, and manipulation. Sorting of the list depends on the type of list we are sorting i.e. if we are sorting integer list then we can use simple sort function whereas if it is a string list then we use compareTo to sort the list.
Sorting an Integer List
An integer list can be sort by the simple sort function.
Example: Sorting an integer list.
Dart
main() {
List< int > geeksforgeeks = [13, 2, -11, 142, -389, 32, 3032, 0];
geeksforgeeks.sort();
print(geeksforgeeks);
}
|
Output:
[-389, -11, 0, 2, 13, 32, 142, 3032]
Sorting a String List
The string is sorted by comparing the length in the sort function.
Example: Sorting a string list.
Dart
main() {
List<String> geeksforgeeks = [ 'one' , 'two' , 'three' , 'four' ];
geeksforgeeks.sort((a, b) => a.length.compareTo(b.length));
print(geeksforgeeks);
}
|
Output:
[one, two, four, three]
If we use sort without comparing the length then:
Example: Sorting a string list without comparing the length.
Dart
main() {
List<String> geeksforgeeks = [ 'one' , 'two' , 'three' , 'four' ];
geeksforgeeks.sort();
print(geeksforgeeks);
}
|
Output:
[four, one, three, two]
Example: Using the cascades method while sorting the list.
Dart
main() {
List< int > geeksforgeeks = [13, 2, -11, 142, -389, 0];
print(geeksforgeeks..sort());
}
|
Output:
[-389, -11, 0, 2, 13, 142]
Last Updated :
29 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...