2

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?

Naman
  • 27,789
  • 26
  • 218
  • 353
Clarinetist
  • 1,097
  • 18
  • 46

2 Answers2

2

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.

Naman
  • 27,789
  • 26
  • 218
  • 353
WJS
  • 36,363
  • 4
  • 24
  • 39
1

Here is a fix for the code in your question. You should take note of this answer though.

double r = IntStream.range(i, j)
                .parallel()
                .mapToDouble(idx -> x[idx])
                .sum();

An even simpler way to achieve the same result would be:

Arrays.stream(x, i, j).parallel().sum();

Note: if you want to sum by length (L) rather than an upper bound, just replace j with i + L in the above code. Your criteria that it should be 1-based is problematic as written, since Java arrays are 0-based by default; working with them as if they are 1-based will eventually cause an IndexOutOfBoundException.

jrook
  • 3,459
  • 1
  • 16
  • 33