WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. Book a mock interview β†’
Expert 73 of 100 Β· Core Java

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

πŸ“• Buy this interview preparation book: 100 Core Java questions & answers β€” PDF + EPUB for $5

thenAccept() is a method in the CompletableFuture class in Java that allows us to specify a callback function to be executed once a CompletableFuture is completed successfully. The method takes a Consumer functional interface as an argument, which will be called with the result of the previous stage.

The thenAccept() method is used when we have a CompletableFuture that returns a result, and we want to execute a callback function that accepts that result and does not return any result. This is similar to the Consumer functional interface.

Here is an example code that shows how to use thenAccept() method:

CompletableFuture<Integer> future =
     CompletableFuture.supplyAsync(() -> 10);
future.thenAccept(result -> System.out.println("Result: " + result));

In this example, we have created a CompletableFuture using the supplyAsync() method, which returns an integer value of 10. We then call the thenAccept() method on the future and pass in a Consumer that takes the result and prints it to the console. The thenAccept() method returns a new CompletableFuture that completes when the Consumer has finished executing.

In summary, the thenAccept() method is used to execute a callback function that accepts the result of the previous stage and does not return a result.

Line open 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 β†’
πŸ“• Buy this interview preparation book: 100 Core Java questions & answers β€” PDF + EPUB for $5

All 100 Core Java questions Β· All topics