简体   繁体   中英

How to get responses in the same order as the original list using parallelStream

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.

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? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM