Java Collections sort() MethodThe 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:
Java Collections sort(list) MethodThis method is used to sort the elements presents in the specified list of collection in ascending order. Java Collections sort(list, comp) MethodThis method is used to sorts the specified list according to the order introduced by the specified comparator. SyntaxFollowing is the declaration of sort() Parameter
ReturnsThe sort() method does not return anything. ExceptionsUnsupportedOperationException- 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 1Test it NowOutput: Specified value before sort: [Java, Python, Android, One, Ruby, Node.js] Specified value after sort: [Android, Java, Node.js, One, Python, Ruby] Example 2Test it NowOutput: Value before sort: [Java, Python, Android, One, Ruby, Node.js] Sort Value according to specified comparator: [Ruby, Python, One, Node.js, Java, Android] Example 3Test it NowOutput: 101 201 230 Example 4Test it NowOutput: 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 Next TopicJava Collections Class |
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