面试题答案
一键面试thenApply方法的作用
CompletableFuture
的thenApply
方法用于对CompletableFuture
异步计算的结果进行转换。它接收一个Function
作为参数,该Function
会在CompletableFuture
完成时被调用,将原计算结果作为输入,并返回转换后的结果。这个方法返回一个新的CompletableFuture
,其结果是对原CompletableFuture
结果应用Function
后的结果。在链式转换操作中,thenApply
起到了将前一个异步操作的结果传递给下一个转换操作的桥梁作用,使得可以在异步任务完成后对结果进行一系列的处理。
示例代码
import java.util.concurrent.CompletableFuture;
public class CompletableFutureThenApplyExample {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> 5)
.thenApply(result -> result * 2)
.thenApply(finalResult -> "计算结果是: " + finalResult)
.thenAccept(System.out::println);
}
}
在上述示例中,supplyAsync
方法异步生成一个整数5
。接着,thenApply
方法将这个整数乘以2
,然后另一个thenApply
方法将计算结果转换为字符串,最后thenAccept
方法将结果打印出来。整个过程展示了如何使用thenApply
方法对CompletableFuture
的计算结果进行链式转换。