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?

pkgajulapalli
  • 1,066
  • 3
  • 20
  • 44
  • 1
    That looks like [`Stream#anyMatch`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#anyMatch-java.util.function.Predicate-)? Or how does that not work for you? – UnholySheep Apr 19 '18 at 07:03
  • No, but you can use a for loop – Maurice Perry Apr 19 '18 at 07:05
  • @UnholySheep That's the correct way to go. You should provide an answer with that suggestion ... – Seelenvirtuose Apr 19 '18 at 07:06
  • I understand, that I can use a for loop or `Stream#anyMatch` for this particular example. But I'm wondering if there is a way to break out of forEach loop. – pkgajulapalli Apr 19 '18 at 07:09
  • 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. – Seelenvirtuose Apr 19 '18 at 07:12
  • @Seelenvirtuose there is, but it's very ugly - throw an Exception – Eugene Apr 19 '18 at 07:16
  • 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. – Seelenvirtuose Apr 19 '18 at 07:17

1 Answers1

14
data.stream().anyMatch(item -> {condition})
piy26
  • 1,574
  • 11
  • 21
  • 1
    I don't think this is correct. What if `condition` is not an expression, but a set of computations? – likejudo Aug 09 '20 at 06:07