thenAccept Signature and Lambda Usage
What you'll learn: How thenAccept accepts a Consumer<T> and how to write clean lambda expressions for it.
Understanding the Consumer<T> Parameter
The thenAccept method has the following signature:
CompletableFuture<Void> thenAccept(Consumer<? super T> action)
This means thenAccept expects a Consumer<T> — a functional interface with a single method void accept(T value). The consumer receives the result of the previous stage but returns nothing (Void).
Writing Concise Lambdas
Because Consumer has one abstract method taking one parameter and returning void, you can write very clean lambda expressions:
Full lambda syntax:
future.thenAccept((String result) -> {
System.out.println(result);
});
Simplified (type inference):
future.thenAccept(result -> {
System.out.println(result);
});
Single-statement (no braces):
future.thenAccept(result -> System.out.println(result));
Method reference (when applicable):
future.thenAccept(System.out::println);
Practical Usage
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenAccept(message -> System.out.println(message)); // Prints: Hello World
The lambda you pass to thenAccept can contain multiple statements if needed:
future.thenAccept(result -> {
logResult(result);
sendNotification(result);
updateDatabase(result);
});
Key Takeaway: thenAccept takes a Consumer<T> lambda that receives the previous stage's result; use concise lambda syntax (often just value -> doSomething(value)) to consume results without returning new values.