Answer the question
In order to leave comments, you need to log in
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;
}
}
for (Item item : items) {
if (item ... pass some condition ...) {
return item.getSomeValue();
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question