Another Version of Reduce

Java-Another Version of Reduce

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:

Another Version of Reduce

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.

Another Version of Reduce

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.

Another Version of Reduce

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.

Another Version of Reduce

The following example shows how this method works on sequential stream.

Another Version of Reduce

The following example shows how this method works on parallel stream.

Another Version of Reduce

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:

Another Version of Reduce

In this example, the reduce() of the parallel stream returns wrong result, the accumulator and the combiner function are one and the same. This results in an error because when two partial results are combined, their squares are sums together rather than the partial results, themselves. The reduce() of the sequential stream return correct result. Because there would have been no need to combine two partial results. The problem occurs when a parallel stream is used. The following example shows how to handle this situation when using parallel stream.

Another Version of Reduce

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

Another Version of Reduce

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);
    }
}

Leave a Comment