0

I tried to use Java 8 parallel stream in one application where I have two long vectors (10,000 dimensional) and need to calculate a quantity using each pair of the values, then find the minimum and its index in the end.

I found a relevant question Java 8 nested loops with streams & performance but still didn't figure it out. Below is an example for making the question clear. any help is appreciated :)

public class dummyCode {
    public static void main(String[] args) {
        double[] a = {1, 2, 3, 4, 5};
        double[] b = {5, 6, 7, 8, 9};
        double min = Double.POSITIVE_INFINITY;
        double root;
        int index = -1;

        for (int i = 0; i < a.length; i++) {
            root = dummyFunction(a[i], b[i]);
            if (root < min) {
                min = root;
                index = i;
            }
        }
        System.out.println("the minimal is " + min + " at index " + index);
    }
    public static double dummyFunction(double a, double b) {
        if (a < 3){
            return a * a - 4 * a * b;
        } else {
            return a + 2 * a * b;
        }
    }
}
Jane
  • 1
  • 4
    If you're using parallel streams, you won't be able to get the index of the minimum element with one pass. If you split the work up it could be done by knowing to offset of the each part that is processed in parallel, but the code would be a bit messy. – Bohemian Nov 19 '19 at 03:16
  • Thanks Bohemian. As with real data the majority of time is spent on calculating all the values, I am thinking first getting them in parallel and then find the index via one more search in the end. Might you point out what method can be used for the first step? it seems for ArrayList there is parallelStream() but I couldn't find the right method for a vector .. – Jane Nov 19 '19 at 03:32
  • No, there's nothing like that for arrays, which you seem to call vectors, you'd have to hand-code it. But why not switch to ArrayLists, there you can stream, thought you still have to zip the two lists to pairs before that step. Or you use a list of pairs instead of two lists of single items. – Curiosa Globunznik Nov 19 '19 at 04:08
  • I see. Sounds like I can either construct ArrayLists for pairs, or write code for arrays. Thank you for your help curiosa! – Jane Nov 19 '19 at 18:03

0 Answers0