Stream.max(Integer::max) : Unexpected result [duplicate]

五迷三道 提交于 2019-11-28 12:14:28

Integer.max(a, b) will return the greater value of the given a and b. If you use that result somehow as a comparator, a positive value returned will be regarded as meaning that a > b so a will be kept.

The first two elements are 3 and 4. Both are positive. Integer.max(3, 4) = 4 > 0. So you're effectively saying that 3 > 4 with such a comparator, so 3 is kept. Then, the same goes for the rest: Integer.max(3, 6) = 6 > 0, so 3 is considered the max, etc.

The contract of a comparator method (on arguments first, second) is:

  • return 0 if first equals second
  • return negative value if first < second
  • return positive value if first > second

The max method with only positive values will always return a positive value. When interpreting the return value according to the comparator contract, a positive value means first > second. As a result, the ordering of items will not change, they appear to be "ordered".

This is unbelievably confusing.

We are trying use Integer::max as a comparator. Since all the numbers in the question are positive, the answer is always interpreted as meaning that the first argument of compare(a, b) is "greater" than the second.

One quirk of Collections.sort is that when you have a list [a, b], the method is programmed in such a way that it is compare(b, a) that is called, rather than compare(a, b) (which would seem more sensible). Hence if compare returns a positive number, it looks like b > a, so the list does not need sorting.

That is why list.sort does nothing.

However it just happens that Stream.max is programmed the other way around, i.e. the first comparison is compare(3, 4), so it looks like 3 is the maximum.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!