如何使用 parallelStream 以与原始列表相同的顺序获取响应
How to get responses in the same order as the original list using parallelStream
我有一个原始列表,我正在该列表上使用并行处理(调用方法)。
想要的是将该方法的响应以与原始列表相同的顺序存储到新列表。
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();
}
这里我希望我的列表与输入数组的顺序相同。
尝试了堆栈溢出的其他一些答案,但没有运气。
感谢任何帮助。
之所以会出现乱序是因为forEach
是一个无序的流终端操作。来自 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.
鉴于此,您可以选择使用 forEachOrdered
替代方法或 map
和 collect
之类的方法来保留顺序。这是 map
和 collect
版本:
inputs.parallelStream()
.map(input -> processStringInput(input))
.collect(Collectors.toList());
此答案中有更多关于有序流与无序流以及顺序流与并行流之间区别的详细信息:。
我有一个原始列表,我正在该列表上使用并行处理(调用方法)。 想要的是将该方法的响应以与原始列表相同的顺序存储到新列表。
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();
}
这里我希望我的列表与输入数组的顺序相同。 尝试了堆栈溢出的其他一些答案,但没有运气。 感谢任何帮助。
之所以会出现乱序是因为forEach
是一个无序的流终端操作。来自 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.
鉴于此,您可以选择使用 forEachOrdered
替代方法或 map
和 collect
之类的方法来保留顺序。这是 map
和 collect
版本:
inputs.parallelStream()
.map(input -> processStringInput(input))
.collect(Collectors.toList());
此答案中有更多关于有序流与无序流以及顺序流与并行流之间区别的详细信息: