Reputation: 13108
As per subject: How can I get the first number greater than 10 in a stream?
Is there any method of stream()
that may help in this case?
I would like that as soon as the stream reaches the first element above 10 it will return it without looping the rest. (kind of "break" the loop) Is it possible?
Upvotes: 1
Views: 6303
Reputation: 37845
You're probably looking for filter
and findFirst
:
// new Random().ints() // or whatever the stream is
.filter(i -> i > 10).findFirst();
findFirst
returns some type of Optional
, so you need to decide what to do with it if you don't find a match.
This is similar to a loop like this:
for (int i : ...)
if (i > 10) // "filter"
return i; // "findFirst" (may or may not be present)
Upvotes: 8