Reduce JavaIn Java, reducing is a terminal operation that aggregates a stream into a type or a primitive type. Java 8 provides Stream API contains set of predefined reduction operations such as average(), sum(), min(), max(), and count(). These operations return a value by combining the elements of a stream. In Java, reduce() is a method of the Stream interface. In this section, we will discuss the Java Stream.reduce() method in detail. It is the method of combining all elements. For each element presented in the stream, the reduce() method applies the binary operator. In that stream, the first argument to the operator must return the value of the previous application and the second argument must return the current stream element. It allows us to produce a single result from a sequence of elements by repeatedly applying a combining operation to the elements in the sequence called reducing. There are the following three variants of Stream.reduce() methods: 1. reduce(BinaryOperator<T> accumulator) It performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any. 2. reduce(Tidentity, BinaryOperator<T> accumulator) Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value. 3. reduce(U identity, BiFunction<U,?super T,U> accumulator, BinaryOperator<U> combiner) Performs a reduction on the elements of this stream, using the provided identity, accumulation, and combining functions. In the above methods, three elements are used as parameter:
Let's take some examples of operations to understand the reduce() method of the Stream class. Java Stream.reduce() ExampleReduceExample1.java Output: ReduceExample2.java Output: ReduceExample3.java Output: ReduceExample4.java Output: ReduceExample5.java Output: Next TopicLRU Cache Implementation In Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India