5

Basically I have a list and its elements will be processed one by one until some condition is met. If that condition is met for any element, it should return true otherwise false. The method looks like:

public boolean method(List<Integer> data) {
    data.forEach(item -> {
        if (some condition is met) {
            return true; //  Getting Unexpected return value here
        }
    });
    return false;
}

Is there a way to break out of this forEach loop right after the condition is met instead of looping through all the elements?

7
  • 1
    That looks like Stream#anyMatch? Or how does that not work for you? Commented Apr 19, 2018 at 7:03
  • No, but you can use a for loop Commented Apr 19, 2018 at 7:05
  • @UnholySheep That's the correct way to go. You should provide an answer with that suggestion ... Commented Apr 19, 2018 at 7:06
  • 5
    "But I'm wondering if there is a way to break out of forEach loop." => No, there isn't. And why should it? There are (better) ways to do that. A forEach simply does what it says: It executes an action for each element, not less. Commented Apr 19, 2018 at 7:12
  • 1
    @Eugene Yes, and that's why I even won't tell someone (especially a beginner) that there is such a possibility. Besides that, it's not only ugly, it uses a mechanism not designed for that purpose. Commented Apr 19, 2018 at 7:17

1 Answer 1

14
data.stream().anyMatch(item -> {condition})
Sign up to request clarification or add additional context in comments.

1 Comment

I don't think this is correct. What if condition is not an expression, but a set of computations?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.