reduce in java 8 streams basic understanding.

aditya chaudhari
JavaDeveloperDiary — JDD
2 min readOct 17, 2021
reduce function in java 8

Using reduce, stream is reduces to a value, in functional paradigm it’s also called as fold.
Reduce is terminal operation in stream API which helps to reduce stream of values to a single value.

Use the reduce operation when you’ve got a collection of values and you want
to generate a single result.

Example code below :

using reduce in java8

Below are the definition for reduce methods.

In example above , line 22 we have used reduce to sum up numbers by providing initial value to consider which is 0. If we do not want to provide initial value its fine , we have overloaded method without initial value only difference is this returns Optional as a return type to handle case where stream could be empty.(Example : line 36).

out of the box operations on primitives like sum, min, max etc are internally use reduce function.

Hope it helps , next time you have a situation where you want to narrow stream to choose only one result based on business logic you ll definitely use reduce.

Thanks for reading.
If you have any suggestions regarding topics or this post please let me know in comments . Your applause would definitely encourage me to write more such content.

All java 8 related articles on this publication can be found here. Sharing is Caring.

--

--

aditya chaudhari
JavaDeveloperDiary — JDD

building efficient, scalable and maintainable enterprise e-commerce applications using java, spring framework and SAP CC. Life Mantra → Love IT Live IT Enjoy IT