Java 8有一个函数CompletableFuture.allOf(CompletableFuture<?>...cfs)
,它返回一个CompletableFuture
在所有给定的期货完成时完成的函数.
但是,我几乎总是不处理一个CompletableFuture
s 数组,而是有一个List<CompletableFuture>
.当然,我可以使用这种toArray()
方法,但是这必须经常在数组和列表之间来回转换,这有点痛苦.
如果有一个光滑的方式来CompletableFuture<List<T>>
换取a List<CompletableFuture<T>>
,而不是经常不得不投入中间数组创建,那将是非常好的.有没有人知道在Java 8中这样做的方法?
为什么CompletableFuture.allOf
声明为CompletableFuture<Void>
和不返回结果集合或其他东西?我认为CompletableFuture.anyOf
返回是个好主意CompletableFuture<Object>
,但我看到这两种方法相互关联,所以我对它们返回的内容感到困惑.
目前要使用 CompletionStage 的集合做一些简单的事情需要跳过几个难看的圈子:
public static CompletionStage<String> translate(String foo) {
// just example code to reproduce
return CompletableFuture.completedFuture("translated " + foo);
}
public static CompletionStage<List<String>> translateAllAsync(List<String> input) {
List<CompletableFuture<String>> tFutures = input.stream()
.map(s -> translate(s)
.toCompletableFuture())
.collect(Collectors.toList()); // cannot use toArray because of generics Arrays creation :-(
return CompletableFuture.allOf(tFutures.toArray(new CompletableFuture<?>[0])) // not using size() on purpose, see comments
.thenApply(nil -> tFutures.stream()
.map(f -> f.join())
.map(s -> s.toUpperCase())
.collect(Collectors.toList()));
}
Run Code Online (Sandbox Code Playgroud)
我想写的是:
public CompletionStage<List<String>> translateAllAsync(List<String> input) {
// allOf takes a collection< futures<X>>, …
Run Code Online (Sandbox Code Playgroud) 我有一个异步执行的查询输入流。我想确保当我使用时Completablefuture::join
,这些要求的结果是按照输入查询流的顺序收集的。
这是我的代码的样子:
queries.stream()
.map(query -> CompletableFuture.supplyAsync(() -> {
try {
return SQLQueryEngine.execute(query);
} catch (InternalErrorException e) {
throw new RuntimeException(e);
}
}))
.map(CompletableFuture::join)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
SQLQueryEngine.execute(查询); 返回一个List<Results>
so 输出是List<List<Result>
。我想展平并将所有结果合并到一个列表中。如果我在收集之前使用 .flatMap(List::stream) 来扁平化,它会保持排序吗?
我有期货清单
List<Future<Boolean>> futures = service.invokeAll( Arrays.asList( callable1, callable2 ));
Run Code Online (Sandbox Code Playgroud)
我需要的是一种获取结果列表的方法
可以提供Java解决方案吗?
就像是 whenAll()...