在 completionstage 的链式调用中,可以直接将函数式接口(如 function、consumer)作为参数传递给 thenapply、thenaccept 等方法。这些方法会自动接收上游阶段的结果并执行对应的逻辑,最终通过 tocompletablefuture() 获取可组合的 completablefuture 实例。

thenApply 如何转换数据流
thenApply 接收一个 Function 函数式接口,用于对上游结果进行转换并返回新值。它适用于需要修改或提取数据的场景,例如从异步任务返回的对象中提取关键字段。

import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
CompletableFuture<string> stage = CompletableFuture.supplyAsync(() -> "Hello World");
// 使用 Function 转换数据
Function<string string> transformer = s -> s.toUpperCase();
CompletableFuture<string> result = stage.thenApply(transformer).toCompletableFuture();
System.out.println(result.join());
}
}</string></string></string>
thenAccept 如何处理副作用
thenAccept 接收一个 Consumer 函数式接口,用于消费上游结果但不返回任何值。它适用于日志记录、数据库写入等不需要返回值但会产生副作用的操作。

import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
CompletableFuture<integer> stage = CompletableFuture.supplyAsync(() -> 42);
// 使用 Consumer 处理副作用
Consumer<integer> handler = n -> System.out.println("Result: " + n);
stage.thenAccept(handler).toCompletableFuture();
}
}</integer></integer>
空值输入对函数式接口的影响
当上游阶段返回 null 时,传递给 thenApply 或 thenAccept 的函数式接口会接收到 null 值。如果函数内部未做空值检查,直接调用对象方法会导致 NullPointerException。因此,在使用函数式接口前需确保上游结果的合法性或在 lambda 表达式中加入防御性判断。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











