- A+

Category：Languages

This question already has an answer here:

I have this exercise and I don't understand the last result:

`import java.util.Arrays; import java.util.Comparator; import java.util.List; public class Test { public static void main(String[] args) { List<Integer> list = Arrays.asList(10, 20, 8); System.out.println(list.stream().max(Comparator.comparing(a -> a)).get()); //Line 1 System.out.println(list.stream().max(Integer::compareTo).get()); //Line 2 System.out.println(list.stream().max(Integer::max).get()); //Line 3 } } `

The result is: `20 20 10`

If `Integer::max`

works like `Math::max`

, it should return the largest value between two elements. So, the max element of list is 20.

Why is the result 10?

`Integer.max`

returns the larger of the two integers.

As such, `Integer.max(10, 20)`

returns 20. 20 is greater than zero, so by the contract of `Comparator.compare`

(which is that `compare(a, b)`

returns a number greater than zero if `a > b`

), 10 is considered "greater than" 20.

Similarly, `Integer.max(10, 8)`

returns 10, greater than zero, so 10 is "greater than" 8.

As such, the final "max" is 10.