Dart – Sort a List

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Main fumction
main() {
    
  // Creating List
  List<int> geeksforgeeks = [13, 2, -11, 142, -389, 32, 3032, 0];
    
  // Sorting List
  geeksforgeeks.sort();
    
  // Printing Sorted List
  print(geeksforgeeks); 
}

chevron_right


 



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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
}

chevron_right


 

Output:

[one, two, four, three]

If we use sort without comparing the length then:

Example: Sorting a string list without comparing the length.



Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
}

chevron_right


 

Output:

[four, one, three, two]

Example: Using the cascades method while sorting the list.

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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());
}

chevron_right


 

Output:

[-389, -11, 0, 2, 13, 142]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.