Java Lambda Expression for if condition - not expected here -


consider case if condition needs evaluate array or list. simple example: check if elements true. i'm looking generic way it

normally i'd that:

boolean alltrue = true; (boolean bool : bools){     if (!bool) {         alltrue = false;         break;      } } if (alltrue){      // } 

but i'd hide if condition. tried using lambda expressions this, it's not working:

if (() -> {     (boolean bool : bools)         if (!bool)             return false;     return true; }){       // } 

if working more complicated like

if (() -> {    int number = 0;    (myobject myobject : myobjects)        if (myobject.getnumber() != 0)            numbers++;    if (numbers > 2)         return false;    return true;  }{      //do  } 

is there better way syntax error?

update i'm not talking boolean array, rather looking generic way achieve that.

you can write, given instance list<boolean>:

if (!list.stream().allmatch(x -> x)) {     // not every member true } 

or:

if (list.stream().anymatch(x -> !x)) {     // @ least 1 member false } 

if have array of booleans, use arrays.stream() obtain stream out of instead.


more generally, stream providing elements of (generic) type x, have provide predicate<? super x> .{all,any}match() (either "full" predicate, or lambda, or method reference -- many things go). return value of these methods self explanatory -- think.


now, count elements obey predicate, have .count(), can combine .filter() -- also takes (whatever is) predicate argument. instance checking if have more 2 elements in list<string> length greater 5 you'd do:

if (list.stream().filter(s -> s.length() > 5).count() > 2l) {     // yup... } 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -