posted 11 months ago

- 3

One of those trick questions, of which the amount seems to be infinite...

The 'stream.max' method takes a Comparator, in this case Comparator<Integer>.

Its method 'compare(int x, int y) returns a positive value if x > y, a negative value if x < y and 0 if x equals y.

Now look at your specific Comparator: compare(x, y) = Integer.max(x, y).

Since in your code x and y are positive, this "Integer.max" gives a positive result. That means that with this Comparator, x is always considered to be bigger than y when x > 0.

Can you now explain why the outcome of the second println is '3'?

The 'stream.max' method takes a Comparator, in this case Comparator<Integer>.

Its method 'compare(int x, int y) returns a positive value if x > y, a negative value if x < y and 0 if x equals y.

Now look at your specific Comparator: compare(x, y) = Integer.max(x, y).

Since in your code x and y are positive, this "Integer.max" gives a positive result. That means that with this Comparator, x is always considered to be bigger than y when x > 0.

Can you now explain why the outcome of the second println is '3'?