Java 如何在循环中调用completable future并合并所有结果?

Java 如何在循环中调用completable future并合并所有结果?,java,completable-future,Java,Completable Future,我正在努力实现这样的目标。这是一个表达意图的虚构示例 我希望所有可完成的未来都执行并将其所有结果合并为一个结果,然后返回该结果。因此,对于下面的示例,集合allResults应该有字符串“one”、“two”、“three”,每个字符串3次。我希望它们都并行运行,而不是串行运行 任何关于我可以在可完成的未来使用什么API来实现这一点的指针都将非常有用 public class Main { public static void main(String[] args) {

我正在努力实现这样的目标。这是一个表达意图的虚构示例

我希望所有可完成的未来都执行并将其所有结果合并为一个结果,然后返回该结果。因此,对于下面的示例,集合allResults应该有字符串“one”、“two”、“three”,每个字符串3次。我希望它们都并行运行,而不是串行运行

任何关于我可以在可完成的未来使用什么API来实现这一点的指针都将非常有用

public class Main {


    public static void main(String[] args) {

        int x = 3;
        List<String> allResuts;

        for (int i = 0; i < x; i++) {

           //call getCompletableFutureResult() and combine all the results
        }

    }

    public static CompletableFuture<List<String>> getCompletableFutureResult() {

        return CompletableFuture.supplyAsync(() -> getResult());
    }

    private static List<String> getResult() {


        List<String> list = new ArrayList<>();
        list.add("one");
        list.add("two");
        list.add("three");

        return list;
    }


}
公共类主{
公共静态void main(字符串[]args){
int x=3;
列出所有结果;
对于(int i=0;igetResult());
}
私有静态列表getResult(){
列表=新的ArrayList();
列表。添加(“一”);
列表。添加(“两个”);
列表。添加(“三”);
退货清单;
}
}

您无法在第一个
for
循环中收集结果,因为这意味着您在等待前一个任务的结果时,甚至没有启动其他任务

因此,一旦所有任务开始,就开始收集结果

public static void main(String[] args) throws Exception
{
  int x = 3;

  Queue<CompletableFuture<List<String>>> cfs = new ArrayDeque<>(x);
  for (int i = 0; i < x; i++)
  {
    cfs.add(getCompletableFutureResult());
  }

  List<String> allResuts = new ArrayList<>();
  for (CompletableFuture<List<String>> cf : cfs)
    allResuts.addAll(cf.get());

  System.out.println(allResuts);
}
publicstaticvoidmain(字符串[]args)引发异常
{
int x=3;
队列cfs=新的阵列队列(x);
对于(int i=0;i
文卡塔·拉朱的回答有问题。Raju在future上使用了get调用,这是一个阻塞调用,扼杀了异步风格编码的主要目的。永远避免做“未来”的事情

有大量的内置方法围绕着处理未来的值而构建,比如apply、accept、compose、combine等等

CompletableFuture.allOf
方法用于处理多个期货

它有以下签名

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
定义combine。在执行'cf.get()`时,它将进行此阻塞,不是吗@venkataYes@AbhinavRavi。这是阻塞。
public class DorjeeTest {


    public static CompletableFuture<List<String>> getCompetableFutureResult() {
        return CompletableFuture.supplyAsync(() -> getResult());
    }
    public static List<String> getResult() {
        return Lists.newArrayList("one", "two", "three");
    }

    public static void testFutures() {
        int x = 3;
        List<CompletableFuture<List<String>>> futureResultList = Lists.newArrayList();
        for (int i = 0; i < x; i++) {
            futureResultList.add(getCompetableFutureResult());
        }

        CompletableFuture[] futureResultArray = futureResultList.toArray(new CompletableFuture[futureResultList.size()]);

        CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(futureResultArray);

        CompletableFuture<List<List<String>>> finalResults = combinedFuture
                .thenApply(voidd ->
                        futureResultList.stream()
                                .map(future -> future.join())
                        .collect(Collectors.toList()));

        finalResults.thenAccept(result -> System.out.println(result));
    }


    public static void main(String[] args) {
        testFutures();
        System.out.println("put debug break point on this line...");

    }
}