Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream's max(Math::max) [duplicate]

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?

like image 452
lbrobinho Avatar asked Apr 09 '26 20:04

lbrobinho


1 Answers

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())
   ....
like image 158
Eugene Avatar answered Apr 11 '26 08:04

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!