reduce() example



import java.util.Arrays;
import java.util.List;

public class ReduceFlight {
public static void main(String[] args) {
List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7);
int sum = nums.stream().reduce(0, (n1,n2)->n1+n2);
System.out.println("Sum="+sum); 
}
}
Output:
Sum=28

Explanation:
reduce is used to convert all values of stream into a single element. It means it is used to reduce stream.
reduce(0, (n1,n2)->n1+n2): it takes two arguments
1st argument is an initial value.
2nd argument is BinaryOperator<T>. It takes two elements in argument and return new element.

int sum = numbers.stream().reduce(0, Integer::sum);
you can also use method reference to find sum of all elements of stream.

int product = nums.stream().reduce(1, (n1,n2)->n1+n2);
above is another line of code to find product of the numbers in list.

Optional<Integer> sum = 
numbers.stream().reduce((n1, n2) -> (n1 + n2));
Above is another line of code which doesnt take initial values in argument.
It takes only one BinaryOperator<T> argument as lamda expression. But here it returns Optional in result. Because if there is no element in the stream then result sum will be absent.
so, we can check in the optional object whether the result is available or not using isPresent() method.