Java 8 Lambdas max() on stream using Integer.max as comparator

Viewed 4005

I have written simple List with example values, and I wanted the stream to return max value from Stream. I know max() function takes Comparator but it turned out, I can pass also Integer::max (anyone can explain my, why?).

Moreover, program prints weird result, I inspected it "inside" and it looks OK, but after I get final result - they are not accurate.

Example:

@Test
public void testHowIntegerMaxWorksInStream() {
    List<Integer> list = Arrays.asList(5,3,8);
    Optional<Integer> op = list.stream().max((a, b) -> {
        System.out.println("Input arguments a=" + a + ", b=" + b);

        int max = Integer.max(a, b);
        System.out.println("Returning max(a,b)=" + max);
        return max;
    });
    System.out.println("Optional result=" + op.get());
}

Output:

Input arguments a=5, b=3
Returning max(a,b)=5
Input arguments a=5, b=8
Returning max(a,b)=8 // OK, Integer::max got 8.. but then ...
Optional result=5 // .. I got 5. WHY ???

My questions:

  1. Why can I pass Integer::max in place of Comparator ?
  2. Why my function returns 5 as a result while inside it's 8 ?
3 Answers
Related