reduce()
Is a terminal operation in the Java Stream API that combines elements in a stream one by one to generate a value. in other words,reduce()
By applying binary operations to elements in the stream (an operation that receives two input parameters and returns a result), multiple elements are "reduced" into a value.
1. The role of the reduce() method
reduce()
Used to generate a single result from a stream, common uses are:
- Calculate the sum and multiply product
- Calculate the maximum value and minimum value
- Combine strings, objects, etc. into one result
reduce()
The operation accepts two parameters:
- An initial value (called "identification").
- A binary operator, usually provided in the form of a lambda expression.
The final result is an Optional value that represents the reduction result of the stream. Commonly used overloading forms are as follows:
2. Three overload forms of reduce() method
Form 1:reduce(BinaryOperator<T> accumulator)
This form has no initial value, and the first element of the stream will be used as the initial value. The return isOptional<T>
, to prevent the flow from being empty.
Optional<Integer> sum = () .reduce((a, b) -> a + b);
Form 2:reduce(T identity, BinaryOperator<T> accumulator)
This form has an initial valueidentity
, it can ensure that there will be a default result even if the stream is empty. The return isT
。
int sum = () .reduce(0, (a, b) -> a + b);
Form 3:reduce(U identity, BiFunction<U, T, U> accumulator, BinaryOperator<U> combiner)
This form is suitable for parallel flow operations, which can separate the accumulator and the merger through two functions. It is usually used to merge by block operation when executing tasks in parallel.
int sum = () .reduce(0, (partialResult, element) -> partialResult + element, // Accumulator Integer::sum); // Merge
3. Example of reduce()
Let's understand it through a few specific examplesreduce()
How to use.
1. Calculate the sum
Suppose we have a list of integers and want to passreduce()
Calculate the sum of all integers:
List<Integer> numbers = (1, 2, 3, 4, 5); // Use a reduce with initial valueint sum = () .reduce(0, (a, b) -> a + b); // The initial value is 0(sum); // Output:15
explain:
reduce(0, (a, b) -> a + b)
:here0
is the initial value,(a, b) -> a + b
It is an accumulator, and each element in the stream is accumulated with the previous calculation result to obtain the final sum.
2. Calculate the product
You can still use itreduce()
Computes the product of all elements. Suppose we want to calculate the product of a list of integers:
List<Integer> numbers = (1, 2, 3, 4, 5); int product = () .reduce(1, (a, b) -> a * b); // The initial value is 1(product); // Output:120
explain:
reduce(1, (a, b) -> a * b)
: The initial value is 1 (because the unit element of the multiplication is 1), and the product of all elements is calculated by cumulative multiplication.
3. String concatenation
Suppose we have a set of strings that we want to passreduce()
Concatenate them and generate a long string.
List<String> words = ("Hello", "World", "Stream", "API"); String result = () .reduce("", (a, b) -> a + " " + b); // The initial value is an empty string(result); // Output:" Hello World Stream API"
explain:
reduce("", (a, b) -> a + " " + b)
: The initial value is an empty string""
, generate the final result by adding each word to the previous string.
4. Find the maximum value
Suppose we want to find the maximum value in a list of integers:
List<Integer> numbers = (1, 2, 3, 4, 5); int max = () .reduce(Integer.MIN_VALUE, (a, b) -> a > b ? a : b); // The initial value is Integer.MIN_VALUE(max); // Output:5
explain:
reduce(Integer.MIN_VALUE, (a, b) -> a > b ? a : b)
: The initial value isInteger.MIN_VALUE
, indicating the smallest possible value. By comparing each element in the stream, you finally find the largest one.
5. Find the minimum value
Similarly, we can usereduce()
Find the minimum value:
int min = () .reduce(Integer.MAX_VALUE, (a, b) -> a < b ? a : b); // The initial value is Integer.MAX_VALUE(min); // Output:1
4. Reduce() without initial value
If the stream is empty and no initial value is usedreduce()
, the returned one will beOptional
Object. This is because if the stream is empty, there is no value to "reduce", so the result is empty.
Example:
List<Integer> emptyList = new ArrayList<>(); Optional<Integer> result = () .reduce((a, b) -> a + b); // No initial value(result); // Output:
explain:
becauseemptyList
is empty, no initial value, soreduce()
Return an emptyOptional
Object, indicates that there is no element to "reduce".
5. Reduce() in parallel streams
In parallel streams (parallelStream()
),reduce()
A third overload method can be used to efficiently process large data sets. It splits the stream into multiple substreams and processes it in parallel through the accumulator and the merger.
Examples in parallel streams:
int sum = () .reduce(0, (partialResult, element) -> partialResult + element, Integer::sum); (sum); // Output:15
explain:
reduce(0, (partialResult, element) -> partialResult + element, Integer::sum)
: The accumulator here is(partialResult, element) -> partialResult + element
, the merger isInteger::sum
, They help merge the results of multiple substreams in parallel streams.
6. Comparison of reduce() with other terminal operations
-
collect()
: Used to collect the elements of the stream into a collection, e.g.List
、Set
orMap
。 -
forEach()
: Used to traverse each element in the stream, perform operations, but do not return the result. -
count()
: Used to count the number of elements in the stream.
andreduce()
It is to "reduce" all elements in the stream into a single result. It is not used for collection or traversal, but for generating an aggregated value.
Summarize
-
reduce()
Is an operation used to aggregate or "reduce" elements in a stream. - It combines multiple elements in the stream one by one through binary operators to generate a single result.
- Typical usages include summing, product, string concatenation, finding maximum and minimum values.
- Using no initial value
reduce()
When the result isOptional
, to prevent the flow from being empty. - In parallel streams,
reduce()
Big data can be processed in parallel through accumulators and mergers.
passreduce()
, you can perform complex aggregation operations on data in streams with very flexible flexibility.
This is the end of this article about Java Stream reduce(). For more related Java Stream reduce() content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!