Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 CompletableFuture.allOf(...) with Collection or List [duplicate]

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?

like image 644
therealrootuser Avatar asked Mar 05 '16 04:03

therealrootuser


1 Answers

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

like image 189
Deepak Avatar answered Oct 20 '22 03:10

Deepak