Out of Collection.forEach() by the condition?

Good afternoon.

I understand that after the appearance of Java 8 it's been a long time, but nevertheless the use case Collection.forEach() is everywhere the same - we go through all items in the collection and each item do something.

But if I need to implement another fairly common scenario. The goal is to go smoothly until, until I something do not find in the collection:

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


Is there a possibility to do it in the style of Java 8?

Often in these cycles, I would like to make an exit from the method:
for (Item item : items) {
 if (item pass ... some condition ...) {
 return item.getSomeValue();
}
}


Is it possible in the style of Java 8?
July 9th 19 at 13:36
3 answers
July 9th 19 at 13:38
Solution
If you need this, then you misunderstand the nature of the streaming API. forEach() is not a cycle in its usual peremptory sense. The correct solution is to pre-filter the stream to forEach() received only the desired values. Or one need. If it is very necessary, from stream to iterator and around it in the classic while(iterator.hasNext()).
July 9th 19 at 13:40
Solution
If you discard any sugar that remains? And will perform the specific method for each element. And neither the 1st nor the second there is not a ride.
But koycheva I can advise. Cause at the beginning of the Stream
July 9th 19 at 13:42
Solution
forEach is used to enumerate all elements
The first example is written like that
items.stream().anyMatch(item -> /* pass some condition */);

And the second can be written as
items.stream().filter(item -> /* pass some condition */).findFirst();
// or so
items.stream().filter(item -> /* pass some condition */).findAny();

Both methods return Optional.
Liked your answer, because with the example code. Thank you. - gregoria commented on July 9th 19 at 13:45
: thank you - charity84 commented on July 9th 19 at 13:48

Find more questions by tags Java