Java
CompletableFuture
继承了CompletionStage
和Future
接口。
CompletableFuture.thenApply
继承自CompletionStage
。
thenApply
返回一个新的CompletionStage
,当该阶段正常完成时,将使用该阶段的结果作为所提供函数的参数来执行该过程。
从Java
文档中找到thenApply
的方法声明。
<U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn)
类型参数U
是函数的返回类型。
fn
参数是用于计算返回的CompletionStage
的值的函数。
thenApply
方法返回CompletionStage
。
thenApply()
可用于对另一个任务的结果执行一些额外的任务。
示例1: 我们创建一个CompletionStage
来执行某些任务,然后在此阶段的结果上,我们使用thenApply
应用函数来执行其他任务。
ThenApplyDemo1.java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ThenApplyDemo1 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture<String> cfuture =
CompletableFuture.supplyAsync(() -> "Krishna").thenApply(data -> "Shri "+ data);
String msg = cfuture.get();
System.out.println(msg);
}
}
输出
Shri Krishna
示例2:
ThenApplyDemo2.java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ThenApplyDemo2 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture<String> cfuture =
CompletableFuture.supplyAsync(() -> computeArea(20, 30)).thenApply(data -> prettyPrint(data));
String msg = cfuture.get();
System.out.println(msg);
}
private static int computeArea(int a, int b) {
return a * b;
}
private static String prettyPrint(int area) {
return "Area: "+ area;
}
}
输出
Area: 600
示例3:
ThenApplyDemo3.java
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class ThenApplyDemo3 {
public static void main(String[] args) throws InterruptedException {
List<Integer> list = Arrays.asList(10, 20, 30, 40);
list.stream().map(num -> CompletableFuture.supplyAsync(() -> num * num))
.map(cfuture -> cfuture.thenApply(res -> "Square: " + res)).map(t -> t.join())
.forEach(s -> System.out.println(s));
}
}
输出
Square: 100
Square: 400
Square: 900
Square: 1600
参考文献
【1】Java Doc: Class CompletableFuture
【2】Java CompletableFuture supplyAsync()
【3】Java CompletableFuture thenApply()