我有以下方法工作正常。我正在尝试完成所有事情并获得该可选流中的值
无需进行额外的 if 检查。是否可以在索引 0 处映射并获取 Result 对象?请指教谢谢。
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);
如果您喜欢方法引用,并且发现 lambda 很无聊
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);
我出于教育原因展示了它,即使我喜欢它,我也不提倡它。
关于java - 如何为可选流中的列表映射索引 0 处的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61062249/