[英]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
是一個無序的流終端操作。 從文檔:
對於並行流管道,此操作不保證遵守流的遇到順序,因為這樣做會犧牲並行性的好處。
鑒於此,您可以選擇使用類似forEachOrdered
替代品或map
和collect
類的東西來保留訂單。 這是map
和collect
版本:
inputs.parallelStream()
.map(input -> processStringInput(input))
.collect(Collectors.toList());
在這個答案中有更多關於有序流與無序流和順序流與並行流之間區別的詳細信息: 如何確保 java8 流中的處理順序? .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.