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

感情迁移 提交于 2019-12-03 04:56:05

问题


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?


回答1:


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());
    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



来源:https://stackoverflow.com/questions/35809827/java-8-completablefuture-allof-with-collection-or-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!