Java 8 has a function CompletableFuture.allOf(CompletableFuture<?>...cfs)
that returns a CompletableFuture
that is completed when all the given futures complete.
However, I almost always am not dealing with an array of CompletableFuture
s, but instead have a List<CompletableFuture>
. Of course, I can use the toArray()
method, but this ends up being a bit of a pain to have to constantly convert back and forth between arrays and lists.
It would be really nice if there were a slick way get a CompletableFuture<List<T>>
in exchange for a List<CompletableFuture<T>>
, instead of constantly having to throw in an intermediary array creation. Does anyone know a way to do this in Java 8?
Unfortunately, to my knowledge CompletableFuture does not support collections.
You could do something like this to make the code a bit cleaner, but it essentially does the same thing
public <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> futuresList) {
CompletableFuture<Void> allFuturesResult =
CompletableFuture.allOf(futuresList.toArray(new CompletableFuture[futuresList.size()]));
return allFuturesResult.thenApply(v ->
futuresList.stream().
map(future -> future.join()).
collect(Collectors.<T>toList())
);
}
Found this very informative : http://www.nurkiewicz.com/2013/05/java-8-completablefuture-in-action.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With