thenApply()和thenCompose()的區別

來源:互聯網
上載者:User

標籤:let   總結   區別   com   sys   span   ret   color   轉換   

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

thenApply()和thenCompose()的區別

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.