使用 thenapply 可以将 completablefuture 的异步计算结果转换为另一种类型。它接收一个 function<t r></t> 函数式接口,将上游完成后的值 t 映射为新的值 r,并返回一个新的 completablefuture<r></r>。如果上游任务抛出异常或结果为空,转换函数不会执行,新 future 会直接携带异常状态。

如何对字符串长度进行转换
当需要获取异步任务的字符串长度时,可以直接在 thenApply 中调用 String.length()。这会将 CompletableFuture<string></string> 转换为 CompletableFuture<integer></integer>。以下代码展示了从模拟耗时任务到获取长度的完整流程。

import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello World");
// 将 String 转换为 Integer (长度)
CompletableFuture<Integer> lengthFuture = future.thenApply(s -> s.length());
System.out.println(lengthFuture.get());
}
}如何将结果封装为自定义对象
如果需要将原始数据包装成特定的业务对象,可以在 thenApply 中实例化该对象。例如将用户 ID 和名称组合成 UserDTO。这种方式保持了链式调用的流畅性,且转换逻辑与主业务解耦。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.CompletableFuture;
class UserDTO {
private final int id;
private final String name;
public UserDTO(int id, String name) { this.id = id; this.name = name; }
@Override public String toString() { return "UserDTO{id=" + id + ", name='" + name + "'}"; }
}
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<Object[]> future = CompletableFuture.supplyAsync(() -> new Object[]{101, "Alice"});
// 将 Object[] 转换为 UserDTO
CompletableFuture<UserDTO> dtoFuture = future.thenApply(arr ->
new UserDTO((Integer) arr[0], (String) arr[1])
);
System.out.println(dtoFuture.get());
}
}转换函数中发生异常会怎样
如果在 thenApply 提供的函数内部抛出运行时异常(如 NullPointerException),下游的 CompletableFuture 将进入异常状态。此时调用 get() 会抛出 ExecutionException。可以通过 exceptionally 或 handle 来捕获并处理这些转换阶段的错误。

















