Repaso
Español
Java CoreAdvancedJV-32

What is the practical difference between thenApply and thenCompose in CompletableFuture?

Options

  1. There is no difference at all, both are the same method
  2. thenApply maps a result; thenCompose flattens futures (Correct option)
  3. thenCompose blocks the thread; thenApply does not
  4. thenApply handles the errors; thenCompose does not

Answer

thenApply transforms the result with a normal function; thenCompose is for a function that itself returns a CompletableFuture and flattens it (like flatMap)

Why

A CompletableFuture<T> represents a result that will exist later, without blocking while you wait.

thenApply(f): when the result arrives, apply a plain function T -> U and get a CompletableFuture<U>.

thenCompose(f): use when f itself returns a CompletableFuture<U> (for example, another async call). Without it you would get a nested CompletableFuture<CompletableFuture<U>>.

It is the same idea as map vs flatMap.

CompletableFuture<Order> order =
    findUserAsync(id)                       // CF<User>
        .thenCompose(u -> findOrderAsync(u)) // CF<Order>
        .thenApply(o -> o.withTax());

Remember

thenApply = map. thenCompose = flatMap.

Key terms

Practice this question in Repaso