Java List.sort() Method24 Mar 2025 | 3 min read The sort() method is used to sort the elements of a List in ascending order according to their natural ordering or using a custom Comparator provided by the user. The List interface belong to the java.util package. It extends the Collection interface. The list must be modifiable else it will throw an exception. SyntaxParametersThe parameter 'c' represents the Comparator used to compare list elements. And for null values, natural ordering is used. ReturnNA Exceptions: ClassCastException: It is thrown if the list contains elements that are not mutually comparable and the natural ordering of these elements is not defined. UnsupportedOperationException: It is raised if the list-iterator of the specified list doesn't support set operation during sorting. It can happen, for example, if an immutable data structure backs the list or if the iterator of the list does not support modification operations. IllegalArgumentException: It is thrown if the contract of the Comparator has been violated. For example, the comparator could return inconsistent results when comparing certain elements, or an exception could be thrown when comparing elements. NullPointerException: The exception can be thrown in a number of situations:
ConcurrentModificationException: This exception can be raised if the list is structurally modified while sorting is going on. For instance, when new elements are added, removed, or modified in the list while the sort() method is running without proper synchronization. Example 1JavaListSortExample.java Output: Original List: [Renu, Heera, Vijay, Geetanjali] Sorted List (Ascending Order): [Geetanjali, Heera, Renu, Vijay] Sorted List (Descending Order): [Vijay, Renu, Heera, Geetanjali] Example 2EmployeeSortingExample.java Output: Unsorted List : 1. 15019 Patanjali 2. 13198 Geetanjali 3. 12112 Anjali Sorted List : 1. 12112 Anjali 2. 13198 Geetanjali 3. 15019 Patanjali Next TopicJava List |
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India