在java中,使用 completablefuture 的 thenapply 方法可以对异步计算的结果进行同步转换。调用该方法的对象必须已经完成或正在执行,传入一个 function<t r></t> 函数式接口,该方法会在原任务完成后立即在当前线程(如果已完成)或原任务的完成线程中执行,并将转换后的新结果封装成一个新的 completablefuture<r></r> 返回。

如何链式调用 thenApply 处理字符串长度
当需要将异步获取的字符串转换为整数(如字符串长度)时,可以直接在 thenApply 中编写转换逻辑。例如,假设有一个异步任务返回用户姓名,我们想获取其长度,可以在 thenApply 中调用 String.length()。这种转换是同步执行的,不会阻塞其他异步流程,但会阻塞当前等待结果的线程直到转换完成。

import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello World");
// 使用 thenApply 将 String 转换为 Integer (长度)
CompletableFuture<Integer> lengthFuture = future.thenApply(s -> s.length());
System.out.println(lengthFuture.get()); // 输出: 11
}
}thenApply 与 thenAccept 的区别是什么
thenApply 和 thenAccept 的主要区别在于返回值。thenApply 接收输入并返回一个新的值,因此它返回的是一个新的 CompletableFuture,可以继续链式调用。而 thenAccept 只消费输入,不返回任何值(返回 void),因此它返回的是 CompletableFuture<void></void>,通常用于副作用操作如打印日志或保存数据库,不能继续基于结果进行数据转换。
使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Data");
// thenApply: 有返回值,可链式调用
CompletableFuture<Integer> applied = future.thenApply(s -> s.length());
// thenAccept: 无返回值,仅消费
future.thenAccept(s -> System.out.println("Consumed: " + s));
System.out.println(applied.get());
}
}如果 thenApply 中的函数抛出异常会发生什么
如果在 thenApply 提供的函数实现中抛出了未捕获的异常,后续的 CompletableFuture 将会进入异常状态(exceptionally completed)。此时,调用 get() 会抛出 ExecutionException,其 Cause 为原始异常。为了处理这种情况,可以链式调用 exceptionally 方法来提供默认值或错误处理逻辑,从而恢复正常的流。

















