带有Collection或List的Java 8 CompletableFuture.allOf(...) [英] Java 8 CompletableFuture.allOf(...) with Collection or List
问题描述
Java 8有一个函数 CompletableFuture.allOf(CompletableFuture<?> ... cfs)
,返回 CompletableFuture
在所有给定的期货完成时完成。
Java 8 has a function CompletableFuture.allOf(CompletableFuture<?>...cfs)
that returns a CompletableFuture
that is completed when all the given futures complete.
但是,我几乎总是没有处理<$ c $的数组c> CompletableFuture s,但是具有 List< CompletableFuture>
。当然,我可以使用 toArray()
方法,但是这必须经常在数组和列表之间来回转换,这有点痛苦。
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.
如果有一个光滑的方式获得 CompletableFuture< List< T>>
,那将是非常好的交换列表< CompletableFuture< T>>
,而不是经常投入中间数组创建。有没有人知道在Java 8中这样做的方法?
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 completable futures 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())
);
}
发现这个非常有用的信息: http://www.nurkiewicz.com/2013/05/java-8-completablefuture-in-action。 html
Found this very informative : http://www.nurkiewicz.com/2013/05/java-8-completablefuture-in-action.html
这篇关于带有Collection或List的Java 8 CompletableFuture.allOf(...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!