Basic thenApply Example: String to Integer
You'll learn how to transform a CompletableFuture<String> into a CompletableFuture<Integer> using thenApply to convert text into its length.
The Core Idea
thenApply lets you take the result from one asynchronous computation and transform it into something else. Think of it like an assembly line: the first station produces a String, and thenApply is the next station that measures and records its length as an Integer. The transformation happens automatically when the original result becomes available.
String Length Example
Here's a simple demonstration where we complete a CompletableFuture with a String and use thenApply to extract its length:
CompletableFuture<String> nameFuture = CompletableFuture.completedFuture("Alice");
CompletableFuture<Integer> lengthFuture = nameFuture.thenApply(name -> name.length());
System.out.println(lengthFuture.join()); // Prints: 5
The lambda name -> name.length() receives the String value ("Alice") and returns an Integer (5). The thenApply method wraps this result in a new CompletableFuture<Integer>.
Method Chaining in Action
You can chain this directly without intermediate variables:
CompletableFuture<Integer> result = CompletableFuture.completedFuture("Hello, World!")
.thenApply(text -> text.length());
System.out.println(result.join()); // Prints: 13
The transformation is declarative—you're describing what should happen to the result, not when or how the threading works. That's handled automatically by the CompletableFuture framework.
Key Takeaway: thenApply transforms a CompletableFuture's result type through a synchronous function, creating a pipeline where String inputs become Integer outputs (or any other transformation you define).