Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
fnFunction<? 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:

18

Handling 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

Related recipes

In the tutorial

  • CompletableFuture — Asynchronous chains in Java — CompletableFuture.supplyAsync, thenApply, thenAccept, thenCombine, allOf, handling errors with exceptionally and join.

Thanks for reading!

Donate to the site — we work hard for you.