Course contentsShow
← Java
Lesson 2818 of 2,87051. CompletableFutureFree lesson

thenCompose vs thenApply: When to Use Which

Compare thenCompose (for functions returning CompletableFuture) with thenApply (for functions returning plain values).

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 transforming String → Integer)
  • thenCompose: Use when your function takes a value and returns a CompletableFuture (like calling another async operation)

Think of It This Way

Imagine you're processing an order:

  • thenApply is like applying a simple calculation: "Take the price and add tax" → you get a number directly
  • thenCompose is like triggering another async step: "Take the order ID and fetch customer details from a database" → you get a promise of customer details (another CompletableFuture)

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.