Converting sum of a subset to stream that can be executed in parallel

Clarinetist :

Consider the following:

import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.DoubleStream;

public class Test {

    public static double sum(double[] x, int i, int L) {
        double s = 0;
        int hi = i + L;
        while (i < hi) {
            s += x[i - 1];
            i++;
        }
        return s;
    }

    /*public static double streamSum(double[] x, int i, int L) {
        return IntStream.range(0, x.length)
                        .parallel()
                        .filter(j -> (j < i + L))
                        .mapToObj(j -> x[j - 1])
                        .sum();
    }*/

    public static void main(String[] argv) {
        double[] x = {1, 2, 3, 4};
        System.out.println(sum(x, 1, 3));

    }

}

sum above takes the array x and (based on 1-indexing - don't ask why, it has to be that way) takes a starting index i and obtains a subset of length L, summing over said subset. An example is given in main above.

How do I fix streamSum above so that I get the same output as sum except using a parallel stream?

WJS :

You said you wanted to sum a sub array starting at i for length L. You should do it like this.

double r = IntStream.range(i, L+i)
            .parallel()
            .mapToDouble(id -> x[id-1])
            .sum();

System.out.println(r);

The reason to subtract 1 is to account for the 1 based index requirement.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=374591&siteId=1