Stream API in Java 8: How to use the reduce() method to perform aggregation operations on collections
Introduction:
In Java 8, the Stream API was introduced, which provides a more powerful and convenient ways to work with collection data. The reduce() method in the Stream API plays an important role in the aggregation operation of the collection. This article will introduce the use of the reduce() method and provide some code examples.
1. Overview of the reduce() method
The reduce() method is one of the core methods in the Stream API for aggregation operations on collections. It accepts a parameter of type BinaryOperator, which defines how the collection elements are aggregated. The reduce() method applies the aggregation operation to the elements of the collection one by one and returns an optional result.
The reduce() method has two overloaded versions:
The first version of the reduce() method accepts an initial value identity and a binary operator accumulator. It takes the initial value as the starting point of the calculation and applies each element to the accumulator, finally returning the aggregated result.
The second version of the reduce() method only accepts a binary operator accumulator. It does not provide an initial value, so it returns an Optional object representing possible results.
2. Examples of using the reduce() method
The following are some code examples showing different uses of the reduce() method:
Yes Sum of collection elements:
List
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out .println(sum); // Output: 15
Find the maximum value of the collection elements:
List
Optional
.reduce(Integer::max);
System.out.println(max.orElse(0)); // Output: 5
Concatenate strings:
List
String result = strings.stream()
.reduce("", (a, b) -> a + " " + b);
System.out.println(result); // Output: Java Stream API
Custom aggregation operation:
List
new Person("Alice", 20),
new Person("Bob", 30),
new Person("Charlie", 25)
);
int totalAge = people.stream()
.reduce(0, (sum, p) -> sum + p.getAge(), (a, b) -> a + b);
System.out.println(totalAge); // Output: 75
In this example, we use a custom Binary operator that sums the ages of Person objects.
Conclusion:
The reduce() method is one of the important methods in the Stream API for collection aggregation operations. Through the reduce() method, we can perform operations such as summing the elements of the set, taking the maximum value, and concatenating strings. In actual development, we can customize binary operators as needed to implement more complex aggregation operations. Proficient in using the reduce() method can make our code more concise and efficient.
The above is the detailed content of Stream API in Java 8: How to use the reduce() method to perform aggregation operations on collections. For more information, please follow other related articles on the PHP Chinese website!