3

When I did the test, I meet a problem with the stream.

The code is below:

public class HelloWorld {
    public static void main(String []args) {

    List<Integer> integers = Arrays.asList(-2, -5, -7, -16);
    Integer integer = integers.stream().max(Math::max).orElse(0);
    System.out.println(integer);

    }
} 

The return value is -15, the minimum number in the list. But when I change max() to min(), it returns me the max value. Why?

Naman
  • 27,789
  • 26
  • 218
  • 353
lbrobinho
  • 143
  • 1
  • 11

1 Answers1

7

This is somehow very subtle, let's take two at a time:

 -2, -5 => Max between these two is "-2"

It is a negative result, since max method from a stream accepts a Comparator, which says:

returns a negative integer if the first argument is less than the second.

Thus according to your Comparator , you have just said that -5 > -2 or in simpler words:

Stream.of(-2, -5)
            .max(Math::max)
            .ifPresent(System.out::println); // will show -5

You can build your logic for the other numbers from here and understand why -16 is the result that you get.

To make this correct, you need:

 ...max(Comparator.naturalOrder())
   ....
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Could you please explain why I compare " -2, -5" twice, which first we compare inside Math::max, and then compare in the max()? – lbrobinho Oct 17 '18 at 16:08
  • @lbrobinho I don't understand your comment, sorry. Think about it a bit, `stream::max` expects a `Comparator` and you say that this `Comparator` is implemented by using `Math::max` – Eugene Oct 17 '18 at 16:13
  • So it is related with the order right? – lbrobinho Oct 17 '18 at 16:19
  • @lbrobinho again, I am not in the world of reading minds here... *what* order? – Eugene Oct 17 '18 at 16:20
  • 2
    if the array is -16, -7 ,-5, -2, so it is correct answer, and I tried naturalOrder(), and understand what you said. Thank you. – lbrobinho Oct 17 '18 at 16:24