簡體   English   中英

如何為可選 Stream 中的列表的索引 0 處的 map 值

[英]How to map value at index 0 for a list in an Optional Stream

我有以下工作正常的方法。 我正在嘗試完成所有事情並在 Optional stream 中獲取值,而無需進行額外的 if 檢查。 是否可以 map 並在索引 0 處獲得結果 object? 請指教謝謝。

public String getData(HttpEntity<Request> request, String endPoint){
    ResponseEntity<Reponse> response = 
        template.exchange(endPoint, HttpMethod.POST, request, Reponse.class);

    List<Result> results = Optional.ofNullable(response)
        .map(ResponseEntity::getBody)
        .map(Response::getQueryResult)
        .map(QueryResult::getResults)
        // getResults is an ArrayList of Result Objects. Could I get the Result Object at index 0 here? 
        // following that I plan to go .map(Result::getValue) here. 
        .orElse(null);
    if(CollectionUtils.isNotEmpty(results)){
        return results.get(0).getValue();
    }
    return null;
}
return Optional.ofNullable(response)
               .map(ResponseEntity::getBody)
               .map(Response::getQueryResult)
               .map(QueryResult::getResults)
               .filter(CollectionUtils::isNotEmpty)
               .map(list -> list.get(0)) // hate this part :)
               .map(Result::getValue)
               .orElse(null);

如果您是方法引用的粉絲,並且發現 lambdas 很無聊

return Optional.ofNullable(response)
               .map(ResponseEntity::getBody)
               .map(Response::getQueryResult)
               .map(QueryResult::getResults)
               .filter(CollectionUtils::isNotEmpty)
               .map(List::iterator)
               .map(Iterator::next)
               .map(Result::getValue)
               .orElse(null);

我出於教育原因展示它,即使我喜歡它,我也不提倡它。

假設ArrayList永遠不是null

.flatMap(r -> r.stream().findFirst())

這需要列表,流式傳輸,獲取帶有第一個元素的Optional (或者如果列表為空,則為空Optional 。最后,由於Optional<Optional<Result>>沒有那么有用,我們使用flatMap而不是map將其折疊成Optional<Result>

更改orElse以從那里返回一個empty列表和stream 通過這種方式,您可以安全地調用findFirst - 至於一個空 List,它將返回Optional::empty並從那里返回 - 您可以將其 map (如果您擁有它)到Result::getValue或者,如果是這樣的 List不存在 - null ,因此它與您的程序流程完全相同。

...
   .map(QueryResult::getResults)
   .orElse(Collections.emptyList())
   .stream()
   .findFirst()
   .map(Result::getValue)
   .orElse(null);

暫無
暫無

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

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