thenApply
和thenCompose
都是对一个CompletableFuture返回的结果进行后续操作,返回一个新的CompletableFuture。
不同
先来看看两个方法的声明描述:
<U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn)
<U> CompletionStage<U> thenCompose(Function<? super T,? extends CompletionStage<U>> fn)
可以看到,两个方法的返回值都是CompletionStage<U>
,不同之处在于它们的传入参数fn
.
- 对于
thenApply
,fn
函数是一个对一个已完成的stage或者说CompletableFuture的的返回值进行计算、操作; - 对于
thenCompose
,fn
函数是对另一个CompletableFuture进行计算、操作。
例子:
CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> 100).thenApply(num -> num + " to String");
CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> 100).thenCompose(num -> CompletableFuture.supplyAsync(() -> num + " to String"));
System.out.println(f1.join()); // 100 to String
System.out.println(f2.join()); // 100 to String
例子中,thApply
和thenCompose
都是将一个CompletableFuture<Integer>
转换为CompletableFuture<String>
。不同的是,thenApply
中的传入函数的返回值是String
,而thenCompose
的传入函数的返回值是CompletableFuture<String>
。就好像stream中学到的map
和flatMap
。回想我们做过的二维数组转一维数组,使用stream().flatMap
映射时,我们是把流中的每个数据(数组)又展开为了流。