Javatpoint Logo
Javatpoint Logo

Java Collections sort() Method

The sort() method of Java Collections class is used to sort the elements presents in the specified list. There is two different types of Java sort() method which can be differentiated depending on its parameter. These are:

  1. Java Collections sort(list) Method
  2. Java Collections sort(list, comp) Method

Java Collections sort(list) Method

This method is used to sort the elements presents in the specified list of collection in ascending order.

Java Collections sort(list, comp) Method

This method is used to sorts the specified list according to the order introduced by the specified comparator.

Syntax

Following is the declaration of sort() method:

Parameter

Parameter Description Required/Optional
list It is the list which will be sorted. Required
comp It is the comparator which determines the order of the list. Required

Returns

The sort() method does not return anything.

Exceptions

UnsupportedOperationException- This method thrown exception if the specified list or its list-iterator does not support the set operation.

ClassCastException- This method thrown exception if the list contains elements that are not mutually comparable (for example, strings and integers).

Example 1

Test it Now

Output:

Specified value before sort: [Java, Python, Android, One, Ruby, Node.js]
Specified value after sort: [Android, Java, Node.js, One, Python, Ruby]

Example 2

Test it Now

Output:

Value before sort: [Java, Python, Android, One, Ruby, Node.js]
Sort Value according to specified comparator: [Ruby, Python, One, Node.js, Java, Android]

Example 3

Test it Now

Output:

101
201
230

Example 4

Test it Now

Output:

Data before sorted-
101 Java USA
103 Ruby China
102 Android India
Data after sorted by rollno-
101 Java USA
102 Android India
103 Ruby China






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA