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

JavaJava 8Completable Future

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontherealrootuserView Question on Stackoverflow
Solution 1 - JavaDeepakView Answer on Stackoverflow