-2

I have an original list and i am using parallel processing on that list(calling a method). What is want is to store the response of that method to a new list in the same order as the original list.

public List<XYZResponse> process(List<String> inputs) {
        List<XYZResponse> myResponse = new ArrayList<>();
        inputs.parallelStream().forEach(input -> {
            myResponse.add(processStringInput(input));
        });
    }
    return myResponse;
}

private XYZResponse processStringInput(String input) {
    return new XYZResponse.Builder().resp(input).build();
}

Here i want my List to be in the same order as the inputs Array. Have tried a few other answers from stack overflow, but with no luck. Any help is appreciated.

whishky
  • 396
  • 3
  • 13
  • 1
    You code doesn’t produce a list at all. In this form, it doesn’t even pass the compiler. – Holger Oct 12 '21 at 09:27
  • If you want it sequential why are you using a parallel stream? – user207421 Oct 17 '21 at 09:07
  • @user207421 why people need parallel stream ? for one for better latencies. And i didn't mention i need sequential, i just need the output coming from the method in the same order, and getting the output in any order and rearranging is also fine for me. – whishky Oct 19 '21 at 22:46

1 Answers1

1

The reason it can come out of order is because forEach is an unordered stream terminal operation. From the docs:

For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.

Given that, you can choose to use something like the forEachOrdered alternative or map and collect to preserve the order. Here's the map and collect version:

inputs.parallelStream()
    .map(input -> processStringInput(input))
    .collect(Collectors.toList());

There are more details about the difference between ordered vs unordered and sequential vs parallel streams in this answer: How to ensure order of processing in java8 streams?.

Marc Baumbach
  • 10,323
  • 2
  • 30
  • 45
  • 1
    Good guesswork. After all, there is no storage operation in the OP’s code at all. – Holger Oct 12 '21 at 09:27
  • Yea, I assumed they were attempting to convert it to a list and may have omitted or struggled to get that part working. This answer was more to help answer the out of order issue mentioned, which seemed to be the primary concern. – Marc Baumbach Oct 12 '21 at 15:25