我正试图实现这样的事情。这是一个表达意图的例子。如何在循环中调用可完成的未来并合并所有结果?
我希望所有完整的期货能够执行并将所有结果合并到一个结果并返回。因此,对于下面的示例,集合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;
}
}
定义_combine_。 –