I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTo
which according to some research is a method for Strings.
I wanted to sort an ArrayList of custom objects by one of their properties: a Date object
(getStartDay()
). Normally I compare them by item1.getStartDate().before(item2.getStartDate())
so I was wondering whether I could write something like:
public class CustomComparator {
public boolean compare(Object object1, Object object2) {
return object1.getStartDate().before(object2.getStartDate());
}
}
public class RandomName {
...
Collections.sort(Database.arrayList, new CustomComparator);
...
}
Since
Date
implementsComparable
, it has acompareTo
method just likeString
does.So your custom
Comparator
could look like this:The
compare()
method must return anint
, so you couldn't directly return aboolean
like you were planning to anyway.Your sorting code would be just about like you wrote:
A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:
Since java-8
You can now write the last example in a shorter form by using a lambda expression for the
Comparator
:And
List
has asort(Comparator)
method, so you can shorten this even further:This is such a common idiom that there's a built-in method to generate a
Comparator
for a class with aComparable
key:All of these are equivalent forms.
Using Java 8 use can define the
Comparator
in one line usingComparator.comparing()
Use any of the following way:
Option 1:
Option 2:
your customComparator class must implement java.util.Comparator in order to be used. it must also overide compare() AND equals()
compare() must answer the question: Is object 1 less than, equal to or greater than object 2?
full docs: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html
Classes that has a natural sort order (a class Number, as an example) should implement the Comparable interface, whilst classes that has no natural sort order (a class Chair, as an example) should be provided with a Comparator (or an anonymous Comparator class).
Two examples:
Usage:
Function & method reference
The
Collections.sort
method can sort aList
using aComparator
you pass. ThatComparator
can be implemented using theComparator.comparing
method where you can pass a method reference as the necessaryFunction
. Fortunately, the actual code is much simpler and shorter than this description.For Java 8:
or
Another way is
From
Java 8
and onward we don't have to useCollections.sort()
directly.List
interface has a defaultsort()
method:See http://visvv.blogspot.in/2016/01/sorting-objects-in-java-8.html.