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;
public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
Function<? super T,? extends U> fn
: This is the function to further process the result of the previous stage.This method returns a new CompletableFuture
.
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());}}
sleep()
that makes the current thread sleep for the given amount of milliseconds.CompletableFuture
using the supplyAsyc()
method. We do this by passing a supplier that sleeps for 4 seconds, printing the current thread of execution, and returning a string value.thenApply()
method to pass an implementation of the Function
interface. This appends a string to the result of supplier passed in line 14.get()
method. We then print it to the console.