Home »
Java programming language
Java Collections sort() Method with Example
Collections Class sort() method: Here, we are going to learn about the sort() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on February 08, 2020
Collections Class sort() method
Syntax:
public static void sort(List l);
public static void sort(List l, Comparator com);
- sort() method is available in java.util package.
- sort(List l) method is used to sort the given list according to natural sorting (i.e. sorting will be in ascending order).
- sort(List l, Comparator com) method is used to sort the given list according to customized sorting (i.e. sorting will be based on the given Comparator com).
-
These methods may throw an exception at the time of sorting the given list.
- ClassCastException: This exception may throw when the given list elements are mutually incomparable.
- UnsupportedOperationException: This exception may throw when the given list un-support set operation.
- These are static methods and it is accessible with the class name and if we try to access these methods with the class object then also we will not get any error.
Parameter(s):
-
In the first case, sort(List l),
- List l – represents the list that is for sorting.
-
In the first case, sort(List l, Comparator com),
- List l – represents the list that is for sorting.
- Comparator com – represents the Comparator with which to calculate the order (ascending or descending) of the given list.
Return value:
In both the cases, the return type of the method is void, it does not return anything.
Example:
// Java program to demonstrate the example
// of sort() method of Collections
import java.util.*;
public class SortOfCollections {
public static void main(String args[]) {
// Instantiates an ArrayList
ArrayList arr_l = new ArrayList();
// By using add() method is to add
// objects in an array list
arr_l.add(20);
arr_l.add(10);
arr_l.add(50);
arr_l.add(40);
arr_l.add(80);
// Display ArrayList
System.out.println("arr_l : " + arr_l);
// By using sort(arr_l,Comparator) method is
// to sort the arraylist by using comparator object
Collections.sort(arr_l, null);
// Display ArrayList
System.out.println("Collections.sort(arr_l, null): " + arr_l);
// By using sort(arr_l) method is
// to sort the arraylist without using
// comparator object
Collections.sort(arr_l);
//Display ArrayList
System.out.println("Collections.sort(arr_l): " + arr_l);
}
}
Output
arr_l : [20, 10, 50, 40, 80]
Collections.sort(arr_l, null): [10, 20, 40, 50, 80]
Collections.sort(arr_l): [10, 20, 40, 50, 80]