Stream reduce(BinaryOperator accumulator) example
Description
Stream reduce(BinaryOperator<T> accumulator)
performs a reduction on the elements of this stream,
using an associative accumulation function,
and returns an Optional describing the reduced value, if any.
Syntax
reduce
has the following syntax.
Optional<T> reduce(BinaryOperator<T> accumulator)
Example
The following example shows how to use reduce
.
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
//w w w . jav a2s . c o m
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> sum = numbers.stream()
.reduce(Integer::sum);
if(sum.isPresent()){
System.out.println(sum.get());
}else{
System.out.println("noValue ");
}
}
}
The code above generates the following result.