Java 8 CompletableFuture.allOf(...) with Collection or List

therealrootuser picture therealrootuser · Mar 5, 2016 · Viewed 86.6k times · Source

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 CompletableFutures, 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?

Answer

Deepak picture Deepak · Mar 5, 2016

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