Java: Stream.Reduce

In this post, we are going to see how we can use Stream reduce operation on a list with an example.

Stream.Reduce()

Stream.Reduce() is a general purpose reduction operation. We can use this operation to process a list and find out the max, min and average value. It’s like applying to a list of values and get a single result value.

The syntax is given below


T reduce(T identity, BinaryOperator accumulator)

Here identity is the initial value and accumulator is a function for combining values.

reduce

In the above example, I have a list of string and want to find out the long string in it. I have used reduce operation to find it out.

Let’s see another example. Assume that we want to process a list and modify the value of it and then reduce the value into a single value. Refer the below example to know how we can achieve this with reduce operation.

reduce-modify-list

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s