Let's take a look at a relatively simple task: You need to sort a list of items (e.g. goods in a shopping basket) by one of its attributes (e.g. price), but want to keep the original order if the sort attribute's value is the same, disregarding other attributes (e.g. product name).
If you do it in Java, it is easy to find the Collections.sort method. Its documentation says: "This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort." However, the method is available with two signatures: One that takes only the list to be sorted and one that lets you specify a comparator explicitly. The point of this post is to explain why it is better to use the latter one.
The sort method that does not specify a comparator uses the so-called natural ordering of the elements, i.e. the order is defined by the compareTo method of the element class. The problem with this is that to prevent possible bugs the natural ordering should be consistent with the equals method, the documentation says: "It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact." But in our case we want to disregard some attributes and keep the original order if the "sort field" value is equals, which means our compareTo has to return 0 even for pairs of elements that are not totally equal.
You may be wondering what bug this could cause. Well, the same element class can be used in many different contexts. One of them may be putting the elements in a SortedSet. And it is easy to overlook this note from its documentation: "Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface." The reason is, the sorted set relies on the ordering of the elements to find out if it contains an element or not. If the compareTo is inconsistent with equals, it would have to go through all elements that are equal according to "compareTo" and check if they are equal according to "equals" as well, and that would make the implementation less efficient.
So the safer solution is to pass the explicit Comparator to the sort method. Using a lambda it is very easy:
Collections.sort(items, (item1, item2) -> item1.price() - item2.price())