如何使用parallelStream处理2个列表



我有两组基于加元和美元的账号。基于这些列表,我需要通过传递请求参数来调用相同的方法,一个用于CAD,另一个用于USD。

List<List<String>> accountNumberList = Arrays.asList(
accountNumbersCAD, accountNumbersUSD
);
List<String> response = new ArrayList<>();
accountNumberList.parallelStream().forEach(s -> {
String response1 = null;
String response2 = null;
try {
response1 = performanceService.retrievePeriodData(reqCAD).toString();
response2 = performanceService.retrievePeriodData(reqUSD).toString();   
} catch (ApiException e) {
}
response.add(response1);
response.add(response2);
});
return (ResponseEntity<String>) response;

请指导我如何使用parallelStream

提前感谢!

不能使用forEach从并行流中填充列表,因为这会导致意外的结果,并且每次生成的列表大小可能不同。相反,使用同步列表或使用collect方法填充列表。

List<Double> response = Collections.synchronizedList(new ArrayList<>());

在我看来,流内部的映射看起来并不复杂,可能没有使用并行流的意义,请自己比较顺序流和并行流的性能。

作为第二个选项,您可以使用collect两次,它应该比使用同步列表更高效。

Function<PerformanceDataRequest, String> mapper = s -> {
try {
return performanceService.retrievePeriodData(s).toString();
} catch (ApiException e) {}
};
List<String> response = accountNumberList.parallelStream().map(mapper.apply(reqCAD)).collect(Collectors.toList());
response.addAll(accountNumberList.parallelStream().map(mapper.apply(reqUSD)).collect(Collectors.toList()));

我不知道reqCAD/reqUSD是什么类型的,所以我用E代替。

最新更新