thenCombine Syntax and BiFunction Parameter
What you'll learn: How the thenCombine method signature uses a BiFunction to merge results from two independent CompletableFuture operations.
The Method Signature
The thenCombine method has the following structure:
<U, V> CompletableFuture<V> thenCombine(
CompletionStage<? extends U> other,
BiFunction<? super T, ? super U, ? extends V> fn)
This looks complex, but breaks down simply: the method takes another CompletableFuture (other) and a BiFunction that knows how to combine both results.
Understanding the BiFunction Parameter
The BiFunction is the heart of thenCombine. It takes two inputs and produces one output:
BiFunction<FirstResult, SecondResult, CombinedResult>
Think of it like mixing ingredients: You have flour (first future) and water (second future), and your BiFunction is the recipe that combines them into dough (combined result).
Basic Syntax Example
CompletableFuture<Integer> future1 = supplyAsync(() -> 10);
CompletableFuture<Integer> future2 = supplyAsync(() -> 20);
CompletableFuture<Integer> combined = future1.thenCombine(
future2,
(result1, result2) -> result1 + result2
);
Here, the BiFunction is the lambda (result1, result2) -> result1 + result2. It receives both integers and produces their sum.
The BiFunction's Role
The BiFunction only executes after both futures complete. It receives:
- The result from the original future (first parameter)
- The result from the
otherfuture (second parameter)
You can perform any logic: addition, concatenation, object creation, comparisons—whatever makes sense for your application.
Key Takeaway: thenCombine uses a BiFunction<T, U, V> to merge two independent future results into a single value, executing the combination logic only after both async operations complete successfully.