How to sort a list in JavaWe can use the following methods to sort the list:
Java Stream interfaceJava Stream interface provides two methods for sorting the list: sorted() methodStream interface provides a sorted() method to sort a list. It is defined in Stream interface which is present in java.util package. It returns a stream sorted according to the natural order. If the elements are not comparable, it throws java.lang.ClassCastException. The signature of the method is: Parameter T: It is a type of stream element. Java Stream.sorted(Comparator comparator)It also returns a stream sorted according to the provided comparator. It is stable for an ordered stream. The signature of the method is: Parameters
Example In the following example, we have used the following methods:
Example Output: Java Comparator.reverseOrder() methodThe reverseOrder() is a method of Comparator interface which is defined in java.util package. The method returns a comparator that imposes the reverse of the natural ordering. It throws NullPointerException when comparing null. The method signature is: Comparable is also an interface belong to a java.lang package. Parameters T: comparable type of element to be compared. Example Output: Java Comparator.naturalOrder()The method returns a comparator that compares Comparable objects in the natural order. The returned comparable is serializable. When we compare null, it throws NullPointerException. It is from Java 8. The signature of the method is:
Parameters T: Comparable type of element to be compared. Example Output: Java Collections.reverseOrder() methodIt is the method of Java Collections class which belong to a java.lang package. It returns a comparator that imposes reverse of the natural ordering. The signature of the method is: Parameters The class of the objects compared by the comparator. Example Output: Java Collections.sort() methodThe Collections class has two methods for sorting a list: sort() methodThe sort() method sorts the list in ascending order, according to the natural ordering of its elements. The signature of the method is: Parameters T: It is a type parameter. list: The list to be sorted. Let's see another example of Collections.sorts() method. Example Output: Next TopicJava Tutorial |
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