簡體   English   中英

零檢查CompletableFuture對象數組

[英]Null check for CompletableFuture Object Array

我正在使用CompletableFuture作為我的一項服務,如下所示 -

CompletableFuture<Employee>[] employeeDetails =
        empIds.stream().map(empId ->
            employeeService.employeeDetails(Integer.valueOf(empId))).toArray(CompletableFuture[]::new);

內部EmployeeService調用API,它返回員工詳細信息。

問題是當API返回null或任何異常時,響應為null。 當我檢查null時,即使employeeDetails數組為null並且其值也為null並且我得到Null Pointer,它總是為false。

我正在檢查null為 -

if(employeeDetails != null && employeeDetails.length > 0){
   //This condition always true even if null values or null array.
   CompletableFuture<Void> allEmployeeDetails = CompletableFuture.allOf(employeeDetails); // Here I am getting NullPointerException
}

我在這里做任何錯誤或CompletableFuture數組需要處理任何特殊檢查。

好吧, CompletableFuture.allOf(employeeDetails)拋出

如果數組或其任何元素為null,則為NullPointerException

您必須檢查數組的所有元素,並且只將非空的元素傳遞給allOf

或者您可以在創建數組之前過濾掉null

CompletableFuture<Employee>[] employeeDetails =
    empIds.stream()
          .map(empId -> employeeService.employeeDetails(Integer.valueOf(empId)))
          .filter(Objects::nonNull)
          .toArray(CompletableFuture[]::new);

這樣你的if語句就足夠了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM