Rollerball
Rollerball

Reputation: 13108

Java 8: how to get the first number greater than 10 in a stream?

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

Answers (1)

Radiodef
Radiodef

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

Related Questions