thenApply和thenCompose的区别

时间:2025-02-13 07:51:44

thenApply()和thenCompose()的区别:

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

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

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


例子:
():

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

      return 100;

});

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

(()); //"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>类型

 

():

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

return 100;

});

CompletableFuture<String> f = ( i -> {

return (() -> {

return (i * 10) + "";

});

});

(()); //1000