How do you sort list of Objects in Java is one of the frequently asked coding
questions in Java interviews and surprisingly not every Java programmers
know How sorting of object happens in Java. Comparator and Comparable interface
along with Collections.sort() method is used to sort list
of object in Java. compare() and compareTo() method of Comparator and Comparable interface
provides comparison logic needed for sorting objects. compareTo()
method is used to provide Object's natural order sorting and compare() method is
used to sort Object with any arbitrary field. Almost all value classes in Java
library e.g. String,
Integer,
Double,
BigDecimal implement compareTo() to specify
there natural sorting order. While overriding compareTo method String is sorted
lexicographically and Integers are sorted numerically. Just beware that it must
in consistent with equals method i.e. two objects which are equal by equals
method in Java, compareTo() method must return zero for
them. Any way, sorting standard value Object is not a problem
for many Java programmer but some of them really struggle when it comes to sort
custom Objects or domain Objects. In this Java sorting tutorial we will
create custom object and sort list of Object in ascending and descending order.