Java 将可完成未来列表转换为列表的一个可完成未来
我有一个Java 将可完成未来列表转换为列表的一个可完成未来,java,java-8,future,completable-future,Java,Java 8,Future,Completable Future,我有一个CompletableFuture实例列表 List<CompletableFuture<String>> listOfFutures; 未来列表; 如何将他们转化为这样一个未来: CompletableFuture<List<String>> futureOfList = convert(listOfFutures); public static <T> CompletableFuture<List<T>
CompletableFuture
实例列表
List<CompletableFuture<String>> listOfFutures;
未来列表;
如何将他们转化为这样一个未来:
CompletableFuture<List<String>> futureOfList = convert(listOfFutures);
public static <T> CompletableFuture<List<T>> convert(List<CompletableFuture<T>> futures) {
return futures.stream().
map(f -> f.thenApply(Stream::of)).
reduce((a, b) -> a.thenCompose(xs -> b.thenApply(ys -> concat(xs, ys)))).
map(f -> f.thenApply(s -> s.collect(toList()))).
orElse(completedFuture(emptyList()));
}
completablefutureofList=convert(未来列表);
这是一个单序列操作。有了(我写的图书馆)你们就可以写作了
AnyM<Stream<String>> futureStream = AnyMonads.sequence(
AsAnyMList.completableFutureToAnyMList(futures));
CompletableFuture<Stream<String>> futureOfList = futureStream.unwrap();
AnyM futureStream=AnyMonads.sequence(
AsAnyMList.CompletableFutureTanymList(期货));
CompletableFutureOfList=futureStream.unwrap();
当您在futureOfList内的流上调用一个终端操作(例如转换为列表)时,它将触发对所有原始futureOfList的join()调用,因此应该以与join()本身类似的方式使用
CompletableFuture completed=futureoff列表。然后应用(
s->s.collect(Collectors.toList());
要为CompletableFuture编写自己的版本,您可以这样做
CompletableFuture<Stream<String>> futureOfList = CompletableFuture.completedFuture(1)
.thenCompose(one->listOfFutures.stream()
.map(cf->cf.join()));
completablefutureofList=CompletableFuture.completedFuture(1)
.thenCompose(一->未来列表.stream()
.map(cf->cf.join());
然后加入
CompletableFuture<List<String>> completed = futureOfList.thenApply(
s->s.collect(Collectors.toList());
CompletableFuture completed=futureoff列表。然后应用(
s->s.collect(Collectors.toList());
另请参阅使用allOf(它不会阻止任何其他线程)的解决方案。您可以这样做:
CompletableFuture<List<String>> futureOfList = convert(listOfFutures);
public static <T> CompletableFuture<List<T>> convert(List<CompletableFuture<T>> futures) {
return futures.stream().
map(f -> f.thenApply(Stream::of)).
reduce((a, b) -> a.thenCompose(xs -> b.thenApply(ys -> concat(xs, ys)))).
map(f -> f.thenApply(s -> s.collect(toList()))).
orElse(completedFuture(emptyList()));
}
公共静态CompletableFuture转换(列表期货){
return futures.stream()。
映射(f->f.thenApply(流::of))。
reduce((a,b)->a.thenCompose(xs->b.thenApply(ys->concat(xs,ys)))。
映射(f->f.thenappy(s->s.collect(toList()))。
orElse(completedFuture(emptyList());
}
看起来像是重复的:-