0

I have an array I want to process in different ways in parallel to speed up the overall runtime of my program. Here is what the program looks like when doing everything sequentially.

public static void main(String[] args) {
    ArrayList<MyObject> array = getLongListOfObjects();
    ArrayList<MyObject2> array2 = new ArrayList<MyObject2>();
    for(MyObject object : array) {
         array2.add(firstProcessingMethod(object);
    }
    ArrayList<MyObject3> array3 = new ArrayList<MyObject3>();
    for(MyObject2 object : array2) {
         array3.add(secondProcessingMethod(object);
    }
    ArrayList<MyObject4> array4 = new ArrayList<MyObject4>();
    for(MyObject3 object : array3) {
         array4.add(thirdProcessingMethod(object);
    }
    for(MyObject4 object : array4) {
         System.out.println(object.toString());
    }
}

In other words I want to start processing the array with firstProcessingMethod() and after the first iteration I can start running secondProcessingMethod() and thirdProcessingMethod() while the rest of the array is still going through firstProcessingMethod().

0

1 Answer 1

4

With Java 8, you can use Streams.

array.parallelStream()
    .map(ThisClass::firstProcessingMethod)
    .map(ThisClass::secondProcessingMethod)
    .map(ThisClass::thirdProcessingMethod)
    .forEach(System.out::println);
Sign up to request clarification or add additional context in comments.

2 Comments

What is ThisClass:: referring to?
It's referring to the class that contains those methods. It's kind of like passing a method as a parameter. For more information, see this question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.