Another Version of Reduce
Suppose you have a stream of objects and want to form the sum of some property, such as all lengths in a stream of strings. For example:
In this case, you can’t use the simple form of reduce. It requires a function (T, T) -> T, with the same types for the arguments and the result.
But in this situation, you have two types: The stream elements have type String, and the accumulated result is an integer(sum of length). There is a form of reduce that can deal with this situation.
In this version, the return type is U. Both accumulator and combiner functions work only if the stream is parallel. If the stream is sequential the accumulator function only work and the combiner function is ignored.
The following example shows how this method works on sequential stream.
In the both example, result are same(25). But this reduce method useful for some situations. For example, suppose you want to get the total of the square of the each element in the Integer stream. Consider the following example:
In this example, the accumulator function sums the identity value and square of each element, but the combiner sums the partial results. Thus, the two functions differ. Moreover, for this computation to work correctly, they must differ.
Program
Program Source
import java.util.stream.Stream; public class Javaapp { public static void main(String[] args) { String strary[] = {"ABC","ABCD","ABCDE","ABCDEF","ABCDEFG"}; Stream<String> strstm = Stream.of(strary); int totalLength = strstm.parallel().reduce(0,(a,b)->a+b.length(),(a,b)->a+b); System.out.println("TotalLength--> "+totalLength); Integer inary[] = {5,10,15,20,25}; Stream<Integer> instm= Stream.of(inary); int totalOfSquare = instm.parallel().reduce(0,(a,b)->a+b*2,(a,b)->a+b); System.out.println("TotalOfSquare--> "+totalOfSquare); } }