CKTIS / Java
CompletableFuture.thenApply: Transform a stage result
Use `thenApply` to transform a stage’s result after it completes normally. It returns a new stage and does not guarantee that the function runs on a separate thread.
Version: Java SE 21
Syntax
public <U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> fn)In Java SE 21, CompletableFuture.thenApply in java.util.concurrent creates a new dependent CompletableFuture<U> without changing the source CompletableFuture<T> result. When the source completes normally, the function receives its result, and the value the function returns becomes the new stage’s result. U can differ from T: ? super T accepts an input type of T or a supertype, and ? extends U accepts a return type of U or a subtype.
The non-async form does not guarantee a separate thread. The function may run on the thread that completes the source, or inline during the thenApply call if the result is already available. Keep these transformations short and non-blocking. thenApplyAsync uses the stage’s default asynchronous execution facility or an explicitly supplied Executor.
If the source completes exceptionally, including through cancellation, the function is skipped and the dependent stage completes exceptionally. The dependent stage also completes exceptionally if the function throws; calling join() on that stage then throws CompletionException instead of returning a result.
Use thenApply when the function returns a plain value. If it returns a CompletionStage<U>, use thenCompose to get that stage’s result without nesting stages.
Examples
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
CompletableFuture<Integer> total = new CompletableFuture<>();
CompletableFuture<String> label = total.thenApply(value -> "Total: " + value);
System.out.println(label.isDone());
total.complete(42);
System.out.println(label.join());
}
}Result
false Total: 42
The first line is `false` because the source is still incomplete. `complete(42)` makes the value available to the function, and `join()` retrieves the transformed result `Total: 42`, waiting if necessary.
Related lessons
- Java · Lesson 51 · Intermediate · Version: 2
Sources
- CompletableFuture.thenApply — Java SE 21 & JDK 21 API
- CompletableFuture — Execution policies and cancellation — Java SE 21 & JDK 21 API
- CompletionStage — Exceptional completion rules — Java SE 21 & JDK 21 API
- CompletionStage.thenCompose — Java SE 21 & JDK 21 API
- CompletableFuture.join — Java SE 21 & JDK 21 API