How to sort a list in Java
We can use the following methods to sort the list:
Java Stream interface
Java Stream interface provides two methods for sorting the list:
Stream 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:
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:
In the following example, we have used the following methods:
Java Comparator.reverseOrder() method
The 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.
T: comparable type of element to be compared.
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:
T: Comparable type of element to be compared.
Java Collections.reverseOrder() method
It 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:
The class of the objects compared by the comparator.
Java Collections.sort() method
The Collections class has two methods for sorting a list:
The sort() method sorts the list in ascending order, according to the natural ordering of its elements. The signature of the method is:
T: It is a type parameter.
list: The list to be sorted.
Let's see another example of Collections.sorts() method.