Sub topic 4
Transforming Results with `thenApply` and `thenAccept`
This chapter assumes you know Java 8 lambdas, generics, CompletableFuture, and basic executor concepts. A CompletableFuture<T> represents an asynchronous computation that will eventually produce a value of type T. You can attach stages to describe what should happen after that value is available.
Transforming a value with `thenApply`
Use thenApply when a completed stage produces a new value. Its function receives the previous result and returns the transformed result.
The returned future has the new type:
CompletableFuture<String> upper =
CompletableFuture.supplyAsync(() -> "hello")
.thenApply(String::toUpperCase);The first future produces a String. The thenApply stage transforms that string into another String. The result is still a CompletableFuture, so more stages can follow it.
import java.util.concurrent.CompletableFuture;
public class TransformDemo {
public static void main(String[] args) {
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> "hello")
.thenApply(String::toUpperCase)
.thenApply(text -> text + " WORLD");
System.out.println(future.join());
}
}The program prints:
HELLO WORLDEach stage receives the value produced by the stage immediately before it. The stages form a pipeline:
thenApply is similar to map in functional programming. It transforms a value without changing the number of values in the pipeline.
Consuming a value with `thenAccept`
Use thenAccept when the next action needs the result but does not produce another value. Its function receives the result and returns void.
import java.util.concurrent.CompletableFuture;
public class ConsumeDemo {
public static void main(String[] args) {
CompletableFuture<Void> printed = CompletableFuture
.supplyAsync(() -> "report ready")
.thenAccept(System.out::println);
printed.join();
}
}This prints report ready. The result of thenAccept is a CompletableFuture<Void>, because the consumer performs an action instead of returning a value.
Use thenApply for calculations, conversions, and preparing data for another stage. Use thenAccept for terminal actions such as displaying a result, writing a record, or sending a notification.
| Method | Function shape | Result |
|---|---|---|
| `thenApply` | `T -> U` | `CompletableFuture<U>` |
| `thenAccept` | `T -> void` | `CompletableFuture<Void>` |
Synchronous stage execution
The plain methods, such as thenApply and thenAccept, may run in the thread that completes the previous stage. If the previous stage has already completed, they may run immediately in the thread that attaches the continuation.
This does not mean that the continuation always runs on the calling thread. It means that no new executor task is required by the plain method.
The thenApplyAsync and thenAcceptAsync variants schedule the continuation asynchronously. You can use the common pool or provide an executor explicitly.
CompletableFuture<String> result = CompletableFuture
.supplyAsync(() -> "data")
.thenApplyAsync(String::toUpperCase);Choose the executor deliberately when the continuation performs blocking input/output or expensive work. A CPU-only transformation is often suitable for the common pool.
Exercise
Exercise
Which method should you use to convert a CompletableFuture<String> into a CompletableFuture<Integer> containing the string length, and which method should you use to print that length without producing another value?
Show answer
Use thenApply(String::length) for the conversion, then use thenAccept(System.out::println) for printing.