我有以下人員類別:class Person { String name; String city; public void setInfo(PersonInformation info) {//...};}我有一個來自此類的對象列表,我想使用返回 CompletableFuture 的方法異步查詢列表中每個項目的數據庫來填充它們的信息:List<CompletableFuture<Void>> populateInformation(List<Person> people) { return people.stream(). .collect(groupingBy(p -> p.getLocation(), toList())) .entrySet().stream() .map(entry -> CompletableFuture.supplyAsync( () -> db.getPeopleInformation(entry.getKey()) ).thenApply(infoList -> { //do something with info list that doens't return anything // apparently we HAVE to return null, as callanbles have to return a value return null; } ) ).collect(Collectors.toList());}問題是我收到編譯錯誤,因為方法中的代碼返回CompletableFuture<List<Object>>而不是CompletableFuture<List<Void>>. 我在這里做錯了什么?我想過刪除return null,但正如我在評論中提到的,似乎在可調用中我們必須返回一個值,否則會出現另一個編譯錯誤:Incompatible types: expected not void but the lambda body is a block that is not value-compatible
2 回答

蕭十郎
TA貢獻1815條經驗 獲得超13個贊
thenApply方法返回類型為CompletableFuture<U>
,這意味著返回 CompletableFuture 并帶有函數返回值
public?<U>?CompletableFuture<U>?thenApply(Function<??super?T,??extends?U>?fn)
返回一個新CompletionStage
值,當此階段正常完成時,將使用此階段的結果作為所提供函數的參數來執行該新值。有關異常完成的規則,請參閱 CompletionStage 文檔。
Type?Parameters: U?-?the?function's?return?type Parameters: fn?-?the?function?to?use?to?compute?the?value?of?the?returned?CompletionStage
使用thenAccept方法返回 Void 類型的 CompletableFuture
public?CompletableFuture<Void>?thenAccept(Consumer<??super?T>?action)
返回一個新的 CompletionStage,當該階段正常完成時,將使用該階段的結果作為所提供操作的參數來執行該階段。有關異常完成的規則,請參閱 CompletionStage 文檔。
Parameters: action?-?the?action?to?perform?before?completing?the?returned?CompletionStage

搖曳的薔薇
TA貢獻1793條經驗 獲得超6個贊
您也可以通過兩種方式強制thenApply
返回 a :CompletableFuture<Void>
指定泛型類型參數:
).<Void>thenApply(infoList?->?{
轉換返回值:
return?(Void)?null;
當然,你可以兩者都做,但那是多余的。
添加回答
舉報
0/150
提交
取消