Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - how to break from a forEach method using lambda expression [duplicate]

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?

like image 200
pkgajulapalli Avatar asked Apr 19 '18 07:04

pkgajulapalli


1 Answers

data.stream().anyMatch(item -> {condition})
like image 50
piy26 Avatar answered Nov 11 '22 09:11

piy26