123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
import java.util.Arrays;
import java.util.List;
public class Common {
public static void main(String[] args) {
List<Integer> ls = Arrays.asList(3, 4, 6, 9, 2, 5, 7);
System.out.println(ls.stream().reduce(Integer.MIN_VALUE, (a, b) -> a > b ? a : b));
System.out.println(ls.stream().max(Integer::max).get());
System.out.println(ls.stream().max(Integer::compare).get());
System.out.println(ls.stream().max((a, b) -> a > b ? a : b));
System.out.println();
System.out.println("USING Integer.max()");
System.out.println(ls.stream().max((o1, o2) -> {System.out.print(o1);
System.out.print(o2);
int max = Integer.max(o1, o2);
System.out.print(max);
System.out.print("\t");
return max;})
.get());
/*
Integer.max() returns the greater of two int values
This is Comparator definition:
A negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
first argument x
second argument y
x<y RETURN negative integer
x=y RETURN zero
x>y RETURN positive integer
This fake "Comparator"'s return statement "return max" always returns positive integers,
meaning max() thinks that first argument which is 3 is always bigger than whatever argument we are comparing it to,
it can be smaller or larger than 3.
So the stream().max() method always thinks that 3 is bigger than whatever is being compared to because the function within max() always returns
positive integers.
In the end 3 was maximum because comparing it to other numbers always yielded positive integer.
*/
System.out.println("USING Integer.compare()");
System.out.println(ls.stream().max((o1, o2) -> {System.out.print(o1);
System.out.print(o2);
int max = Integer.compare(o1, o2);
System.out.print(max);
System.out.print("\t");
return max;})
.get());
/*
Integer.compare() works like this:
(x < y) ? -1 : ((x == y) ? 0 : 1);
This is how stream().max() works here:
1) 3 compared to 4 means Integer.compare() returns -1 so stream().max() gets negative integer meaning that it has not found a max yet so max() moves to next numbers 4 and 6
2) 4 compared to 6 means Integer.compare() returns -1 so stream().max() gets negative integer meaning that it has not found a max yet so max() moves to next numbers 6 and 9
3) 6 compared to 9 means Integer.compare() returns -1 so stream().max() gets negative integer meaning that it has not found a max yet so max() moves to next numbers 9 and 2
4) 9 compared to 2 means Integer.compare() returns 1 so stream().max() gets positive integer meaning it has found the max now as 9 and it keeps the max() to compare to next number 5
5) 4 compared to 6 means Integer.compare() returns 1 so stream().max() gets positive integer meaning it has found the max now as 9 and it keeps the max() to compare to next number 7
6) Now the stream().max() has found the max as 9 and returns it. get() is necessary to get it out of Optional
}
*/
}
}