Java ArrayList sort() Method
The sort() method sorts the elements in the dynamic array according to the specified order.
The syntax of the sort() method is:
arraylist.sort(Comparator c)
Note:arraylist is an object of the ArrayList class.
Parameter Description:
- comparator - the ordering method
Return Value
The sort() method does not return any value; it simply changes the order of the elements in the dynamic array list.
Example
Sort in natural order; the following is the order of the letters:
Example
import java.util.Comparator;
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
sites.add("Example");
sites.add("Google");
sites.add("Wiki");
sites.add("Taobao");
System.out.println("Website list: " + sites);
System.out.println("Unsorted: " + sites);
// Sort the elements in ascending order
sites.sort(Comparator.naturalOrder());
System.out.println("Sorted: " + sites);
}
}
Executing the above program produces the following output:
网站列表: [Example, Google, Wiki, Taobao] 不排序: [Example, Google, Wiki, Taobao] 排序后: [Google, Example, Taobao, Wiki]
In the above example, we used the sort() method to sort a dynamic array named sites.
Note this line:
sites.sort(Comparator.naturalOrder());
Here, the naturalOrder() method of the Java Comparator interface specifies that the elements are sorted in natural order (ascending).
The Comparator interface also provides a method for sorting elements in descending order:
Example
import java.util.Comparator;
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
sites.add("Example");
sites.add("Google");
sites.add("Wiki");
sites.add("Taobao");
System.out.println("Website list: " + sites);
System.out.println("Unsorted: " + sites);
// Descending order
sites.sort(Comparator.reverseOrder());
System.out.println("Descending sort: " + sites);
}
}
Executing the above program produces the following output:
网站列表: [Example, Google, Wiki, Taobao] 不排序: [Example, Google, Wiki, Taobao] 降序排序: [Wiki, Taobao, Example, Google]
In the above example, the reverseOrder() method of the Comparator interface specifies that the elements are sorted in reverse order (descending).
Other Extensions
Java ArrayList