Java Question

Java process array in parallel

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()
.

Answer

With Java 8, you can use Streams.

array.parallelStream()
    .map(ThisClass::firstProcessingMethod)
    .map(ThisClass::secondProcessingMethod)
    .map(ThisClass::thirdProcessingMethod)
    .forEach(System.out::println);