PAA :
I am doing some research on the stream reduce
and trying to run the very simple program.
Why Integer.min
doesn't return the minimum number like Integer.min
return the maximum number ?
public class Reducing {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(3,4,5,1,2);
Integer sum = numbers.stream().reduce(0, (a, b) -> a+ b);
System.out.println("REDUCE : "+sum);
int sum2 = numbers.stream().reduce(0, Integer::sum);
System.out.println(sum2);
int max = numbers.stream().reduce(0, (a, b) -> Integer.max(a, b));
System.out.println("MAX == > "+max);
int min = numbers.stream().reduce(0, (a, b) -> Integer.min(a, b));
System.out.println("MIN == > "+min);
}
}
Output ==>
REDUCE : 15
15
MAX == > 5
MIN == > 0
Aleh Maksimovich :
You are supplying 0
as identity item to min
. This value will also used in computations.
int min = numbers.stream().reduce(0, (a, b) -> Integer.min(a, b));
So virtually it is like having
Arrays.asList(0,3,4,5,1,2)
You shuold omit the identity element in your example
int min = numbers.stream().reduce((a, b) -> Integer.min(a, b)).get();
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=439146&siteId=1