WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Core Java · Expert · question 72 of 100

What is a CompletableFuture thenCombine() method in Java? How is it used?

📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview — then scores it.
📞 Practice Core Java — free 15 min
📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

All 100 Core Java questions · All topics