thenAccept: Consuming Results Without Returning a Value
What you'll learn: How to use thenAccept to process a CompletableFuture's result for side effects without producing a new value.
The Core Idea
While thenApply transforms a result into a new value (think mapping), thenAccept is designed for terminal operations where you want to do something with the result but don't need to return anything. It's like the difference between a function that returns a transformed value versus a void method that performs an action.
Think of it like a package delivery: thenApply is like receiving a package and repackaging it into something new. thenAccept is like receiving the package and actually using what's inside—no repackaging, just consumption.
How thenAccept Works
The thenAccept method takes a Consumer<T> (a function that accepts a value but returns nothing) and returns a CompletableFuture<Void>. This signals that the pipeline continues, but no meaningful value flows through anymore—only completion status.
CompletableFuture.supplyAsync(() -> "Hello, World!")
.thenApply(String::toUpperCase)
.thenAccept(result -> {
// Side effect: print to console
System.out.println("Result: " + result);
// No return value needed
});
When to Use thenAccept
Use thenAccept when you've reached the end of your transformation pipeline and need to:
- Log results
- Update UI components
- Write to databases
- Send notifications
- Any other side-effect operation
Since it returns CompletableFuture<Void>, you can still chain further operations (like exception handling) or block on completion with join().
Key Takeaway: thenAccept is your terminal consumer for CompletableFuture pipelines—use it when you need side effects without producing new values, completing the async computation chain with an action rather than a transformation.