2

I saw this post about reversing order with lambdas, but one thing that's confused me even with traditional Comparator implementations (or anonymous inner classes) is: why does comparing the second argument with the first argument reverse the order?

For example:

public int compare(Integer o1, Integer o2) {
    return o2.compareTo(o1);
}

In the above snippet, integers will be sorted in reverse order. However, o1.compareTo(o2) results in a normal order. Why does switching the order of comparison work, and why does this extend to other custom comparators?

user3882
  • 128
  • 1
  • 4

1 Answers1

2

Remember that when comparing a to b comparator returns 1, 0, and -1 for a > b, a == b and a < b, respectively.

To reverse the order you want -1, 0, and 1 as a result of the comparisons. But to get that to happen you actually must reverse the inequalities and compare b to a.

WJS
  • 36,363
  • 4
  • 24
  • 39