将具有return语句的Java普通for循环转换为Java8 IntStream

Dig*_*tal 3 java java-8

下面是我的普通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)

但如上图所示,在返回时收到错误.

错误:意外的返回值

如何以正确的方式重构上面的代码?

Jac*_* G. 5

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)

  • 值得注意的是,根据`isExist`方法的作用,重写它以获取当前的`History`而不是(可能)通过索引访问`List`可能更好.这将节省大量随机访问`List`. (2认同)