CompletableFuture.thenCombine()
Combines the results of two independent tasks once both are ready.
Available since: Java 8
Syntax
<U, V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, BiFunction<? super T, ? super U, ? extends V> fn)Parameters
| Parameter | Type | Description |
|---|---|---|
| other | CompletionStage<? extends U> | The second, independent task. |
| fn | BiFunction<? super T, ? super U, ? extends V> | Combines both results. |
Return value
CompletableFuture<V>The combined result.
Examples
A price and an exchange rate load in parallel:
void main() {
var price = CompletableFuture.supplyAsync(() -> 120.0);
var rate = CompletableFuture.supplyAsync(() -> 0.92);
double inEuro = price.thenCombine(rate, (p, r) -> p * r).join();
IO.println(inEuro);
}Output:
110.4Notes
Both tasks run at the same time, so the total time equals the longest one. For any number of tasks use CompletableFuture.allOf(...) and then join() each one.
See also
- CompletableFuture.thenApply() — Adds a step that transforms the result once it is ready.
- CompletableFuture.supplyAsync() — Runs a computation asynchronously and returns a `CompletableFuture`.
- BiFunction — A function of two arguments.
Related recipes
In the tutorial
- CompletableFuture — Asynchronous chains in Java — CompletableFuture.supplyAsync, thenApply, thenAccept, thenCombine, allOf, handling errors with exceptionally and join.