CompletableFuture.thenApply()
Adds a step that transforms the result once it is ready.
Available since: Java 8
Syntax
<U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> fn)Parameters
| Parameter | Type | Description |
|---|---|---|
| fn | Function<? super T, ? extends U> | The transformation of the finished result. |
Return value
CompletableFuture<U>A new `CompletableFuture` with the transformed result.
Examples
A chain of steps:
void main() {
int length = CompletableFuture.supplyAsync(() -> " Hello, async world ")
.thenApply(String::strip)
.thenApply(String::length)
.join();
IO.println(length);
}Output:
18Handling an error in the chain:
void main() {
String result = CompletableFuture.supplyAsync(() -> Integer.parseInt("oops"))
.thenApply(n -> "number " + n)
.exceptionally(e -> "failed: " + e.getCause().getMessage())
.join();
IO.println(result);
}Output:
failed: For input string: "oops"Notes
It is the map() of a future result. If the function itself returns a CompletableFuture, use thenCompose(); if the result is not needed further, use thenAccept(). An error at any step skips the following thenApply() calls and reaches exceptionally() or handle().
See also
- CompletableFuture.supplyAsync() — Runs a computation asynchronously and returns a `CompletableFuture`.
- CompletableFuture.thenCombine() — Combines the results of two independent tasks once both are ready.
- Stream.map() — Transforms every element of a stream.
Related recipes
In the tutorial
- CompletableFuture — Asynchronous chains in Java — CompletableFuture.supplyAsync, thenApply, thenAccept, thenCombine, allOf, handling errors with exceptionally and join.