带有集合或列表的 Java 8 CompletableFuture.allOf(...)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35809827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 CompletableFuture.allOf(...) with Collection or List
提问by therealrootuser
Java 8 has a function CompletableFuture.allOf(CompletableFuture<?>...cfs)
that returns a CompletableFuture
that is completed when all the given futures complete.
Java 8 有一个函数CompletableFuture.allOf(CompletableFuture<?>...cfs)
,它返回一个CompletableFuture
在所有给定的期货完成时完成的函数。
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
s数组,而是处理List<CompletableFuture>
. 当然,我可以使用该toArray()
方法,但最终不得不在数组和列表之间不断来回转换有点痛苦。
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?
如果有一种巧妙的方式 get aCompletableFuture<List<T>>
来交换 a List<CompletableFuture<T>>
,而不是不断地投入中间数组创建,那将会非常好。有谁知道在 Java 8 中做到这一点的方法吗?
回答by Deepak
Unfortunately, to my knowledge CompletableFuture does not support collections.
不幸的是,据我所知 CompletableFuture 不支持集合。
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
发现这非常有用:http: //www.nurkiewicz.com/2013/05/java-8-completablefuture-in-action.html