将两个具有不同返回类型的CompletableFuture的结果组合在一起

时间:2019-05-14 12:51:18

标签: java completable-future

我喜欢并行运行2个不同的CompletableFuture(每个都有不同的返回类型),然后合并它们的结果:

 CompletableFuture<Person> person = personDB.asyncCall(..);
 CompletableFuture<Dog> dog = dogDB.asyncCall(...);

现在,我想将dog.name和人名结合起来

return dog.getName() + person.getName()

我正在尝试使用

  CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(perons, dog);
  combinedFuture.thenApply(aVoid -> {
             // now what?
        });

但是在这里很烂。

1 个答案:

答案 0 :(得分:1)

使用get()方法等待它们完成。

CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(perons, dog);
combinedFuture.get(); // wait for all of them to complete
return dog.getName() + person.getName();

请参见https://www.baeldung.com/java-completablefuture

  

请注意,CompletableFuture.allOf()的返回类型是   CompletableFuture。这种方法的局限性在于它确实   不返回所有期货的合并结果。相反,您必须   从期货手动获取结果。幸好,   CompletableFuture.join()方法和Java 8 Streams API使其成为现实   简单: