CompletableFuture: Combining Results of Futures

This lesson explains how we can combine the results of an arbitrary number of futures together.

We'll cover the following

In the previous lesson, we used the thenCombine() and thenCompose() methods to combine the result of two futures.

If we need to run multiple futures in parallel and combine their result then we can use the allOf() and anyOf() methods.

1) allOf()

Here are a few important points regarding allOf() method:

  1. It returns a new CompletableFuture that is completed when all of the given CompletableFutures are completed.

  2. If any of the given CompletableFutures complete exceptionally, the returned CompletableFuture also completes, with a CompletionException holding this exception as its cause.

  3. The results, if any, of the given CompletableFutures are not reflected in the returned CompletableFuture, but they may be obtained by inspecting them individually.

  4. If no CompletableFutures are provided, it returns a CompletableFuture completed with the value null.

Get hands-on with 1200+ tech skills courses.