List of Futures -> Future of List

July 20, 2016

Implementing the sequence function for the Java 8 CompletableFuture

When working with Java 8’s CompletableFuture you may find a yourself in a sitution where you want to start a collection of async operations and block until they have all completed. One way of framing this problem is by thinking in types, which means that we are after a function of type List<CompletableFuture<T>> -> CompletableFuture<List<T>>.

Despite CompletableFuture having over 50 methods this is not actually something they provide out of the box. Fortunately is does have all of the pieces required to write such a function without much effort. The method allOf accepts any number of CompletableFutures and returns a CompletableFutures<Void> that completes when all of the provided futures complete. Once this future completes all that is left is to go back the original futures and gather up the results, giving us the following

(Credit to Misha over on StackOverflow for providing this in an answer)