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<Integer> 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 order
numbers.sort(Comparator.naturalOrder());
System.out.println("Sorted ArrayList: " + numbers);
}
}
// Output: Unsorted ArrayList: [7, 3, 9, -33]
// Sorted ArrayList: [-33, 3, 7, 9]
Syntax 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<String> 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 order
languages.sort(Comparator.naturalOrder());
System.out.println("Sorted ArrayList: " + languages);
}
}
Output
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,
languages.sort(Comparator.naturalOrder());
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<String> 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 order
languages.sort(Comparator.reverseOrder());
System.out.println("Sorted ArrayList: " + languages);
}
}
Output
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.