The Comparable interface defines the compareTo
method used to compare objects.
If a class implements the Comparable interface, objects created from that class can be sorted using Java's sorting algorithms.
The compareTo
method required by the Comparable interface receives as its parameter the object to which the "this" object is compared.
If the "this" object comes before the object received as a parameter in terms of sorting order, the method should return a negative number. If, on the other hand, the "this" object comes after the object received as a parameter, the method should return a positive number. Otherwise, 0 is returned.
The sorting resulting from the compareTo
method is called natural ordering.
If a class implements the Comparable interface, it is possible to sort the list by using the sorted
method.
Be aware, however, that a stream does not sort the original list - only the items in the stream are sorted. If a programmer wants to organize the original list, the sort
method of the Collections
class should be used.
member.stream().sorted().forEach(m -> System.out.println(m));
Collections.sort(member);
<aside>
💡 Implementing Multiple Interfaces
A class can implement multiple interfaces. Multiple interfaces are implemented by separating the implemented interfaces with commas (public class ... implements *FirstInterface*, *SecondInterface* ...
).
</aside>
Both the sort
method of the Collections
class and the stream's sorted
method accept a lambda expression as a parameter that defines the sorting criteria.
More specifically, both methods can be provided with an object that implements the Comparator interface, which defines the desired order - the lambda expression is used to create this object.
persons.stream().sorted((p1, p2) -> {
return p1.getBirthYear() - p2.getBirthYear();
}).forEach(p -> System.out.println(p.getName()));
Collections.sort(persons, (p1, p2) -> p1.getBirthYear() - p2.getBirthYear());
String.compareTo()
also treats letters according to their size, while the compareToIgnoreCase
method of the same class ignores the capitalization completely.
We sometimes want to sort items based on a number of things. We'll make use of Java's Comparator class here, which offers us the functionality required for sorting.
The Comparator
class provides two essential methods for sorting: comparing
and thenComparing
.
The comparing
method is passed the value to be compared first, and the thenComparing
method is the next value to be compared.
The thenComparing
method can be used many times by chaining methods, which allows virtually unlimited values to be used for comparison.
When we sort objects, the comparing
and thenComparing
methods are given a reference to the object's type - the method is called in order and the values returned by the method are compared. The method reference is given as Class::method
.