Home > database >  Returning a negative int literal in comparator lambda-expression sorts list in reverse order
Returning a negative int literal in comparator lambda-expression sorts list in reverse order

Time:11-01

When I use sort() or sorted() on a List or stream respectively, and I pass a lambda expression with an int literal like so:

sorted((s1,s2) -> -500)

I expect the result to have the same order as it had before. But instead the order is reversed. When I return a positive integer, the order stays the same. Why is this? My initial expectation is that it should be the other way around.

CodePudding user response:

The negative answer means that the first is always smaller than the second argument. A simple sorting algorithm (fast for already sorted items) will go from first to last. Evidently the first argument is the following item in the list, so a sorted list is reversed.

However that is a coincidence. The comparison should use both compared values. Otherwise you might even find yourself in an infinite loop when the array is not sorted (when the algorithm is improved), or you are using a parallel stream (very probable).

CodePudding user response:

The lambda is just a call to java.lang.Comparable.compareTo(Object) and the result is interpreted the same way.

In other words:

s1.compareTo(s2)
  • Related