thenCompose vs thenApply: When to Use Which
What you'll learn: How to choose between thenCompose and thenApply based on whether your transformation function returns a plain value or another CompletableFuture.
The Core Difference
The distinction boils down to what your transformation function returns:
thenApply: Use when your function takes a value and returns a plain, unwrapped result (like transformingString → Integer)thenCompose: Use when your function takes a value and returns aCompletableFuture(like calling another async operation)
Think of It This Way
Imagine you're processing an order:
thenApplyis like applying a simple calculation: "Take the price and add tax" → you get a number directlythenComposeis like triggering another async step: "Take the order ID and fetch customer details from a database" → you get a promise of customer details (anotherCompletableFuture)
The Nesting Problem
If you mistakenly use thenApply when your function returns a CompletableFuture, you end up with nested futures:
CompletableFuture<CompletableFuture<String>> nested =
future.thenApply(id -> fetchUserAsync(id)); // Wrong! Nested future
With thenCompose, the result is automatically flattened:
CompletableFuture<String> flat =
future.thenCompose(id -> fetchUserAsync(id)); // Correct! Flat future
Decision Rule
Ask yourself: "Does my transformation function return a CompletableFuture?"
- Yes → Use
thenCompose(for chaining async operations) - No → Use
thenApply(for synchronous transformations)
Key Takeaway: Use thenApply for simple value transformations that return plain results; use thenCompose when your transformation triggers another asynchronous operation that returns a CompletableFuture, avoiding nested futures and keeping your pipeline flat.