Java ArrayList sort[]
In this tutorial, we will learn about the Java ArrayList sort[] method with the help of examples.
The sort[] method sorts the elements in an arraylist according to the specified order.
Example
import java.util.ArrayList; import java.util.Comparator; class Main { public static void main[String[] args] { // create an ArrayList ArrayList numbers = new ArrayList[]; numbers.add[7]; numbers.add[3]; numbers.add[9]; numbers.add[-33]; System.out.println["Unsorted ArrayList: " + numbers]; // sort the ArrayList in ascending orderSyntax of ArrayList sort[]
The syntax of the sort[] method is:
arraylist.sort[Comparator c]Here, arraylist is an object of the ArrayList class.
sort[] Parameters
The sort[] method takes a single parameter.
- comparator - specifies the sort order of the arraylist
sort[] Return Values
The sort[] method does not return any value. Rather it only changes the order of elements in an arraylist.
Example 1: Sort the ArrayList in Natural Order
import java.util.ArrayList; import java.util.Comparator; class Main { public static void main[String[] args] { // create an ArrayList ArrayList languages = new ArrayList[]; // add elements to ArrayList languages.add["Python"]; languages.add["Swift"]; languages.add["C"]; languages.add["JavaScript"]; System.out.println["Unsorted ArrayList: " + languages]; // sort the ArrayList in ascending orderOutput
Unsorted ArrayList: [Python, Swift, C, JavaScript] Sorted ArrayList: [C, JavaScript, Python, Swift]In the above example, we have used the sort[] method to sort the arraylist named languages. Notice the line,
Here, the naturalOrder[] method of the Java Comparator Interface specifies that elements are sorted in natural order [i.e. ascending order].
The Comparator interface also provides a method to sort elements in descending order. For example,
Example 2: Sort the ArrayList in Reverse Order
import java.util.ArrayList; import java.util.Comparator; class Main { public static void main[String[] args] { // create an ArrayList ArrayList languages = new ArrayList[]; // add elements to ArrayList languages.add["Python"]; languages.add["Swift"]; languages.add["C"]; languages.add["JavaScript"]; System.out.println["Unsorted ArrayList: " + languages]; // sort the ArrayList in ascending orderOutput
Unsorted ArrayList: [Python, Swift, C, JavaScript] Sorted ArrayList: [Swift, Python, JavaScript, C]Here, the reverseOrder[] method of the Comparator interface specifies that elements are sorted in reverse order [i.e. descending order].
Note: The Collections.sort[] method is the more convenient method for sorting an arraylist.