面试题答案
一键面试thenApply方法的作用
CompletableFuture
的thenApply
方法用于对CompletableFuture
异步操作的结果进行转换。它接收一个Function
作为参数,该Function
会应用在CompletableFuture
完成时的结果上,并返回一个新的CompletableFuture
,其结果是经过Function
转换后的结果。
使用场景举例
假设我们有一个异步任务用于获取用户ID,然后需要根据这个用户ID去数据库查询用户信息。代码示例如下:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class CompletableFutureExample {
public static CompletableFuture<Integer> fetchUserId() {
return CompletableFuture.supplyAsync(() -> {
// 模拟异步获取用户ID
return 1;
});
}
public static CompletableFuture<User> fetchUserById(int id) {
return CompletableFuture.supplyAsync(() -> {
// 模拟根据ID从数据库查询用户
return new User("John");
});
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<User> userFuture = fetchUserId()
.thenApply(CompletableFutureExample::fetchUserById)
.thenCompose(CompletableFuture::join);
User user = userFuture.get();
System.out.println("User name: " + user.getName());
}
}
在上述代码中,fetchUserId
方法异步获取用户ID,thenApply
方法将获取到的用户ID作为参数传递给fetchUserById
方法,返回一个新的CompletableFuture
,然后通过thenCompose
方法将嵌套的CompletableFuture
展开,最终获取到用户信息。这样就实现了异步操作结果的转换与链式调用,适用于需要对异步任务结果进行进一步处理的场景。