stream().reduce
时间: 2023-09-10 16:10:59 浏览: 90
() method is used to perform a reduction operation on the elements of a stream. The reduction operation combines all the elements of the stream into a single result.
The syntax of the reduce() method is:
```java
Optional<T> reduce(BinaryOperator<T> accumulator)
```
Here, the accumulator is a function that takes two parameters and returns a result of the same type as the parameters.
The reduce() method returns an Optional object that contains the result of the reduction operation. If the stream is empty, the Optional object will be empty.
Example:
```java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> sum = numbers.stream().reduce((a, b) -> a + b);
if (sum.isPresent()) {
System.out.println("Sum of numbers = " + sum.get());
} else {
System.out.println("List is empty");
}
```
Output:
```
Sum of numbers = 15
```
In this example, we have a list of integers and we are using the reduce() method to find the sum of all the numbers in the list. The accumulator function takes two integers and returns their sum. The reduce() method returns an Optional object that contains the sum of the numbers. We are using the isPresent() method to check if the Optional object is empty or not. If it is not empty, we are printing the sum of the numbers. If it is empty, we are printing a message that the list is empty.
阅读全文