When to use Comparable and Comparator

Use Comparable if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this. Use Comparator if you want to define an external controllable ordering behaviour, this can override the default ordering behaviour.

When should a class be Comparable and/or Comparator?

The text below comes from Comparator vs Comparable Comparable A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances. Comparator A comparator object is capable of comparing two different objects. The class is not comparing its instances, … Read more

Comparator.reversed() does not compile using lambda

This is a weakness in the compiler’s type inferencing mechanism. In order to infer the type of u in the lambda, the target type for the lambda needs to be established. This is accomplished as follows. userList.sort() is expecting an argument of type Comparator<User>. In the first line, Comparator.comparing() needs to return Comparator<User>. This implies … Read more

Sort ArrayList of custom Objects by property

Since Date implements Comparable, it has a compareTo method just like String does. So your custom Comparator could look like this: public class CustomComparator implements Comparator<MyObject> { @Override public int compare(MyObject o1, MyObject o2) { return o1.getStartDate().compareTo(o2.getStartDate()); } } The compare() method must return an int, so you couldn’t directly return a boolean like you … Read more

What is the internal sorting technique used in comparator and comparable interfaces and why? [duplicate]

Both Comparable and Comparator are interfaces. All they do is define a way of asking whether one object is greater than, equal to, or less than another. The interfaces don’t enforce what that means — that’s up to the class that implements the interface. So one Comparator<Employee> might say that Adam is “greater than” Bill … Read more