0Pricing
Java Academy · Lesson

Chaining with thenApply and thenCompose

Transform results with thenApply and flatMap async steps with thenCompose to avoid nested futures.

thenApply: Transform the Result

thenApply(Function) applies a synchronous function to the result of a completed future, returning a new future of the transformed type. It does not start a new async task.

CompletableFuture<String> nameFuture = CompletableFuture
    .supplyAsync(() -> 42L)            // CF<Long>
    .thenApply(id -> "User#" + id);    // CF<String>
System.out.println(nameFuture.join()); // "User#42"

thenApplyAsync: Transform on a Thread

thenApplyAsync runs the transformation function on the ForkJoinPool (or a supplied executor), freeing the completing thread immediately.

CompletableFuture<String> result = fetchUserAsync()
    .thenApplyAsync(user -> serialize(user)); // runs on pool thread

All lessons in this course

  1. Creating and Completing CompletableFutures
  2. Chaining with thenApply and thenCompose
  3. Combining Futures: allOf and anyOf
  4. Error Handling and Async HTTP Pipeline
← Back to Java Academy