P
P
Pavel Dudenkov2016-05-17 12:44:17
Java
Pavel Dudenkov, 2016-05-17 12:44:17

Exit Collection.forEach() by condition?

Good afternoon.
I understand that a lot of time has passed since the advent of Java 8, but nevertheless, the scenario for using Collection.forEach() is the same everywhere - we go through all the elements of the collection and do something with each element.
And if I need to implement another fairly typical scenario. The goal is to go exactly until I find something in the collection:

for (Item item : items) {
            if (item  ... pass some condition ...) {
                found = true;
                break;
            }
}

Is it possible to do this in Java 8 style?
More often in such loops, I would like to exit the method:
for (Item item : items) {
            if (item  ... pass some condition ...) {
                return item.getSomeValue();
            }
}

Is this possible in Java 8 style?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-05-17
@viperz

If you need this, then you misunderstand the nature of the streaming API. forEach()is not a cycle in its usual imperative sense. The correct solution is to pre-filter the stream so that forEach()only the necessary values ​​​​are received. Or the right one. If you really need it, then you can get an iterator from the stream and bypass it in the classic while(iterator.hasNext()).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question