Given a collection of futures
final Collection<CompletableFuture<X>> futures = ...;
final CompletableFuture<Collection<X>> joined = ???
How to produce a future for a collection with all values combined together, without calling join
?
Given a collection of futures
final Collection<CompletableFuture<X>> futures = ...;
final CompletableFuture<Collection<X>> joined = ???
How to produce a future for a collection with all values combined together, without calling join
?
The solution is to
Collection<CompletableFuture<X>>
to Collection<CompletableFuture<Collection<X>>>
CompletableFuture.completedFuture(Collections.emptyList())
as initial value.final CompletableFuture<Collection<X>> joined =
futures
.stream()
.map(f -> f.thenApply(value -> (Collection<X>)Collections.singletonList(value)))
.reduce(
CompletableFuture.completedFuture(Collections.emptyList()),
(f, g) ->
f.thenCompose(
xs -> g.thenApply(
ys -> Stream
.of(xs, ys)
.flatMap(Collection::stream)
.collect(Collectors.toList()))
)
);