下面是我的普通for循环,我想重构相同的代码以使用java8 IntStream.
for(int i=0; i<= historyList.size(); i++) {
if (isExist(historyList, status, i)) {
return historyList.get(i).getCreated();
}
}
Run Code Online (Sandbox Code Playgroud)
以下是重构IntStream版本
IntStream.rangeClosed(0, historyList.size()).forEach(i -> {
if (isExist(historyList, status, i)) {
return historyList.get(i).getCreated(); -- Error: Unexpected return value
}
});
Run Code Online (Sandbox Code Playgroud)
但如上图所示,在返回时收到错误.
错误:意外的返回值
如何以正确的方式重构上面的代码?
IntStream#forEach返回nothing(void),因此您无法从其中返回任何数据.相反,您可以map将数据转换为您希望返回的类型,然后返回它(或其他一些值):
return IntStream.rangeClosed(0, historyList.size())
.filter(i -> isExist(historyList, status, i))
.map(historyList::get)
.map(History::getCreated) // Or whatever the object is called.
.findFirst()
.orElse(null); // Or some other value.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |