thenApply()和thenCompose()的区别

thenApply()和thenCompose()的区别:

thenapply()是返回的是非CompletableFuture类型:
它的功能相当于将CompletableFuture<T>转换成CompletableFuture<U>。

thenCompose()用来连接两个CompletableFuture,返回值是新的CompletableFuture:

总结:thenApply()转换的是泛型中的类型,是同一个CompletableFuture;
thenCompose()用来连接两个CompletableFuture,是生成一个新的CompletableFuture。


例子:
1.thenApply():

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {

      return 100;

});

CompletableFuture<String> f = future.thenApplyAsync(i -> i * 10).thenApply(i -> i.toString());

System.out.println(f.get()); //"1000"

thenApply()源码:

public <U> CompletableFuture<U> thenApply(
Function<? super T,? extends U> fn) {
return uniApplyStage(null, fn);
}

解读:
参数: Function<? super T,? extends U> fn)
输入前面的CompletableFuture<T>中的T的值,返回一个继承U的类型的值,将这个值返回

顺序:先确定返回值U或其子类,再确定方法中 public <U> CompletableFuture<U> thenApply()中的 <U>类型

 

2.thenCompose():

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {

return 100;

});

CompletableFuture<String> f = future.thenCompose( i -> {

return CompletableFuture.supplyAsync(() -> {

return (i * 10) + "";

});

});

System.out.println(f.get()); //1000

转载于:https://www.cnblogs.com/tian666/p/7885566.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值