| Start |
|---|
| Sorting a List using Comparable Say we are working on a class representing a Person by their first and last names. We have created a basic class to do this and implemented proper Now we would like to sort a list of Unfortunately, as marked, the above currently won't compile. If you were asked to sort the following list : Now, the main method given will function correctly If, however, you either do not want or are unable to modify class Comparators can also be created/used as an anonymous inner class Lambda expression based comparatorsAs of Java 8, comparators can also be expressed as lambda expressions Comparator default methodsFurthermore, there are interesting default methods on the Comparator interface for building comparators : the following builds a comparator comparing by Inversing the order of a comparatorAny comparator can also easily be reversed using the |
| The compareTo and compare Methods The And the These two methods do essentially the same thing, with one minor difference: Aside from that difference, the two methods have similar requirements. Specifically (for compareTo),
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. (opens new window) Thus, for the comparison of
|
| Natural (comparable) vs explicit (comparator) sorting There are two First, here is a Person class that implements Comparable: Here is how you would use the above class to sort a List in the natural ordering of its elements, defined by the Here is how you would use an anonymous inline Comparator to sort a List that does not implement Comparable, or in this case, to sort a List in an order other than the natural ordering: |
Creating a Comparator using comparing method This creates a comparator for the class Reversed order To create a comparator that imposes the reverse ordering use Chain of comparators This will create a comparator that firs compares with last name then compares with first name. You can chain as many comparators as you want. |
| Sorting Map entries As of Java 8, there are default methods on the Of course, these can also be used outside of the stream api : Syntax
RemarksWhen implementing a The truncation caused by the Instead, the simplest correct implementation is to use Double.compare (opens new window), as such: A non-generic version of It is very standard for a class to be comparable to itself, as in: While it is possible to break from this paradigm, be cautious when doing so. A |
Read Article
https://develop.horje.com/learn/1434/reference