'Merging completable futures
I have a piece of code like this:
public class ProcessorService {
@Autowired private AsyncService asyncService;
public Void process() {
List<CompletableFuture<List<MyEntity>>> futures = new ArrayList<>();
for (i = 0; i < 3; i++) {
futures.add(asyncService.getSomething());
}
List<MyEntity> flatList = sequence(futures); // compile error
}
private static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) {
CompletableFuture<Void> allDoneFuture =
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
return allDoneFuture.thenApply(v ->
futures.stream().
map(future -> future.join()).
collect(Collectors.<T>toList())
);
}
}
The compilation error is:
Required type: List<MyEntity>
Provided: CompletableFuture<List<List<MyEntity>>>
How can I get a list that has all the elements from individual futures merged into one?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
