2016-04-20 46 views
1

最後在Java 8中使用CompletableFuture dealio。我得到一個我不太瞭解的編譯錯誤(在我的IDE中)。Java 8 CompletableFuture.thenApply()

我已經得到了我想要追加到一個URL,然後異步調用每個URL標識的List<String>。到目前爲止,我只有這幾種方法。

private void process(List<String> identifiers) { 

    List<CompletableFuture<String>> futures = identifiers.stream() 
      .map(CompletableFuture.thenApply(this::sendRequest)) 
      .collect(toList()); 
} 

private void sendRequest(String s) { 
     // do some URL building and append the string to the end of the url. 
     // then call it, don't care about result yet 
} 

我得到的編譯器錯誤是在第一個方法的this::sendRequest片。這是抱怨我的班級沒有定義sendRequest(Object)方法。

但我認爲通過鍵入identifiers我不需要擔心我的拉姆達符號呼叫類型?我甚至不知道如何用::運算符指定類型。也許我不應該使用::運營商?我很困惑。

+0

'CompletableFuture.thenApply'我不知道靜態的'thenApply'方法。 – zeroflagL

+0

可悲的是我甚至爲了CompletableFuture拉起了javadoc,並沒有注意到這一點。可能是因爲試圖同時學習lambda函數和CompletableFutures。 – Justin

回答

2

thenApply必須已經存在CompletableFuture對象上調用。例如,

List<CompletableFuture<String>> futures = identifiers.stream() 
     .map(CompletableFuture::completedFuture) // makes CompletableFuture<String> 
     .map(f -> f.thenApply(this::sendRequest)) 
     .collect(toList()); 
+0

我想,這仍然不符合OP的意圖,因爲如果所有事情都在發起者線程內執行,那麼根本無意使用'CompletableFuture'。使用'thenApplyAsync'而不是'thenApply'可以解決這個問題,但是請注意'sendRequest'不返回一個值,所以它不會以這種方式工作,使用'thenAcceptAsync'代替允許調用'void'方法,但是導致'CompletableFuture'不會返回原始的'String'作爲結果... – Holger

+0

@Holger我可能會使用'CompletableFuture'錯誤,因爲我不關心返回值。我只想看看線程的工作。我可能會在'sendRequest'方法中做一個'println'。我不希望它是完全學術的,但我希望我學會順利轉化爲實際解決方案。我認爲@Misha回答了這個問題足以幫助我掌握基本原理,並且您的評論鞏固了它。 – Justin

+0

我做過這樣的事情'List >'我會看看它是如何發展的。 – Justin