Tag: 的未来

列出<未来>到未来<列表>序列

我正在尝试将List<CompletableFuture<X>>转换为CompletableFuture<List<T>> 。 这是非常有用的,因为当你有很多的asynchronous任务,你需要得到所有的结果。 如果其中任何一个失败,那么最后的未来将失败。 这是我已经实现的: public static <T> CompletableFuture<List<T>> sequence2(List<CompletableFuture<T>> com, ExecutorService exec) { if(com.isEmpty()){ throw new IllegalArgumentException(); } Stream<? extends CompletableFuture<T>> stream = com.stream(); CompletableFuture<List<T>> init = CompletableFuture.completedFuture(new ArrayList<T>()); return stream.reduce(init, (ls, fut) -> ls.thenComposeAsync(x -> fut.thenApplyAsync(y -> { x.add(y); return x; },exec),exec), (a, b) -> a.thenCombineAsync(b,(ls1,ls2)-> { ls1.addAll(ls2); return ls1; },exec)); } 运行它: […]