The thenCombine() method of the CompletableFuture class in Java is used to combine the results of two independent CompletableFuture objects. It takes two arguments, the first one is the second CompletableFuture object to be combined, and the second one is a BiFunction object that is used to combine the results of the two CompletableFuture objects.
The BiFunction takes two arguments, which are the results of the two CompletableFuture objects, and returns the combined result. The thenCombine() method returns a new CompletableFuture object that will be completed with the result of the BiFunction.
Here is an example code snippet that demonstrates the use of thenCombine() method:
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 20);
CompletableFuture<Integer> combinedFuture =
future1.thenCombine(future2, (result1, result2) -> result1 + result2);
System.out.println("Combined Result : " + combinedFuture.get());
// Output: Combined Result : 30
In the above example, we create two CompletableFuture objects named future1 and future2. The supplyAsync() method is used to supply the values 10 and 20 to the two CompletableFuture objects asynchronously.
The thenCombine() method is called on the future1 object with the future2 object and a BiFunction object that adds the results of the two CompletableFuture objects. This returns a new CompletableFuture object named combinedFuture.
Finally, the get() method is called on the combinedFuture object to retrieve the combined result, which is 30.