3

Below is my ordinary for loop and I want to refactor the same code to use java8 IntStream.

for(int i=0; i<= historyList.size(); i++) {
            if (isExist(historyList, status, i)) {
                return historyList.get(i).getCreated();
            }
        }

And below is the refactored IntStream version

IntStream.rangeClosed(0, historyList.size()).forEach(i -> {
            if (isExist(historyList, status, i)) {
                return historyList.get(i).getCreated(); -- Error: Unexpected return value
            }
        });

But getting error at the return as shown above.

Error: Unexpected return value

How to refactor the above code in a proper way?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Digital
  • 549
  • 1
  • 7
  • 26

1 Answers1

5

IntStream#forEach returns nothing (void), so you cannot return any data from within it. Instead, you can map the data to the type you wish to return, and then return it (or some other value):

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.
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
  • 2
    Worth noting that depending on what to `isExist` method does, it might be better to rewrite it to take the current `History` rather than (presumably) accessing the `List` by index. That would save a lot of random access to the `List`. – Boris the Spider Feb 03 '18 at 22:53