Combining Results with Lambda Expressions
You'll learn how to use BiFunction lambdas to merge two asynchronous results into a single meaningful value when using thenCombine.
Understanding the Merging Function
When you call thenCombine, you must provide a BiFunction<T, U, R> that takes the results from both CompletableFutures and produces a combined output. This is where lambda expressions shine—they let you concisely express how to merge two independent asynchronous computations.
Think of it like a chef combining ingredients from two prep stations: one station delivers chopped vegetables, another delivers cooked pasta. The chef's combining function determines whether to make a salad, a pasta dish, or something entirely new.
Writing BiFunction Lambdas
The lambda takes two parameters (one from each CompletableFuture) and returns a single result:
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 20);
CompletableFuture<Integer> combined = future1.thenCombine(
future2,
(result1, result2) -> result1 + result2 // BiFunction merges both
);
System.out.println(combined.join()); // Output: 30
You can create any combination logic:
// Concatenating strings
future1.thenCombine(future2, (name, age) -> name + " is " + age + " years old");
// Creating objects
future1.thenCombine(future2, (price, quantity) -> price * quantity);
// Complex business logic
future1.thenCombine(future2, (userData, permissions) ->
new AuthenticatedUser(userData, permissions)
);
The lambda's parameters automatically receive the unwrapped results once both futures complete—you write the merging logic as if working with synchronous values.
Key Takeaway: BiFunction lambdas in thenCombine let you express clear, concise merging logic for two asynchronous results, treating them as regular values without manually managing threading or completion callbacks.