What is CompletableFuture.thenApply() in Java?
thenApply() is an instance method of the CompletableFuture class that processes a stage’s result. It accepts a Function functional interface that accepts an argument and returns a result.
This method also chains multiple stages of computation together. The thenApply() task is run on the same thread as the supplyAsync() task. Alternatively, it is run in the main thread if the supplyAsync() task completes immediately.
Refer to CompletableFuture.thenApplyAsync() if the task in
thenApply()needs to be in a different thread.
The thenApply method is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package.
To import the CompletableFuture class, check the following import statement:
import java.util.concurrent.CompletableFuture;
Syntax
public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
Parameters
Function<? super T,? extends U> fn: This is the function to further process the result of the previous stage.
Return value
This method returns a new CompletableFuture.
Code
Let’s take a look at the code:
import java.util.concurrent.*;public class Main {static void sleep(int millis){try {Thread.sleep(millis);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args) throws ExecutionException, InterruptedException {CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {sleep(1000);System.out.println("Thread execution - " + Thread.currentThread().getName());return "Hello-Educative";});completableFuture.thenApply(res -> res + "-Edpresso");System.out.println("Result - " + completableFuture.get());}}
Explanation
- Line 1: We import the relevant packages and classes.
- Lines 5-11: We define a function called
sleep()that makes the current thread sleep for the given amount of milliseconds. - Line 14: We create a
CompletableFutureusing thesupplyAsyc()method. We do this by passing a supplier that sleeps for 4 seconds, printing the current thread of execution, and returning a string value. - Line 20: We use the
thenApply()method to pass an implementation of theFunctioninterface. This appends a string to the result of supplier passed in line 14. - Line 22: We get the result of the future using the
get()method. We then print it to the console.