如何在CompletableFutures中正确地展开列表



我试图从返回CompletableFuture<List>的方法扇出到每个列表元素的另一个方法,其中风扇反过来也返回每个CompletableFuture。之后,我想从列表产生的期货中返回一个CompletableFuture.allOf

实际上,我有以下方法(假设它们在自己的Service类中,为了简洁起见,我只是将它们组合在一起):

@Async
public CompletableFuture<List<File>> getMatchingCsvFrom(Path directory, Pattern pattern) {
...some work here
}
@Async
public CompletableFuture<Boolean> processSingleCsv(File csvFile) {
...some work here
}

我试着这样称呼他们:

public CompletableFuture<Void> processDirectory(Path directory) {
CompletableFuture<List<File>> matchingCsvFrom = fileProcessingService.getMatchingCsvFrom(directory, PROCESS_PATTERN);
List<CompletableFuture<Boolean>> processFutures = matchingCsvFrom.get().stream()
.map(file -> processService.processProcessCsv(file))
.collect(Collectors.toList());
return CompletableFuture.allOf(processFutures.toArray(new CompletableFuture[0]));
}

.get()显然是一个问题,但我不能解决它使用.thenApply(),.thenAccept(),或.thenCompose()

不幸的是,我发现所有其他答案都想完成相反的事情(从List<CompletableFuture>CompletableFuture<List>)。感谢任何建议!

public CompletableFuture<Void> processDirectory(Path directory) {
CompletableFuture<List<File>> matchingCsvFrom = fileProcessingService.getMatchingCsvFrom(directory, PROCESS_PATTERN);
return matchingCsvFrom.thenCompose( list -> {
var processFutures = list.stream()
.map(file -> processService.processProcessCsv(file))
.collect(Collectors.toList())
.toArray(new CompletableFuture[0]);
return CompletableFuture.allOf(processFutures);
});
}

最新更新