Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Lambda Expression for if condition - not expected here

Consider the case where an if condition needs to evaluate an array or a List. A simple example: check if all elements are true. But I'm looking for generic way to do it

Normally I'd do it like that:

boolean allTrue = true;
for (Boolean bool : bools){
    if (!bool) {
        allTrue = false;
        break;
     }
}
if (allTrue){
     // do Something
}

But now I'd like to hide it into my if condition. I tried using Lambda Expressions for this, but it's not working:

if (() -> {
    for (Boolean bool : bools)
        if (!bool)
            return false;
    return true;
}){
      // do something
}

If this were working I could do something more complicated like

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

Is there a better way to do it is it just a syntax error?

UPDATE I'm not talking about the boolean array, rather looking for a generic way to achieve that.

like image 777
Patrick Avatar asked Dec 02 '22 20:12

Patrick


1 Answers

You can write, given for instance a List<Boolean>:

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

Or:

if (list.stream().anyMatch(x -> !x)) {
    // at least one member is false
}

If you have an array of booleans, then use Arrays.stream() to obtain a stream out of it instead.


More generally, for a Stream providing elements of (generic) type X, you have to provide a Predicate<? super X> to .{all,any}Match() (either a "full" predicate, or a lambda, or a method reference -- many things go). The return value of these methods are self explanatory -- I think.


Now, to count elements which obey a certain predicate, you have .count(), which you can combine with .filter() -- which also takes (whatever is) a Predicate as an argument. For instance checking if you have more than 2 elements in a List<String> whose length is greater than 5 you'd do:

if (list.stream().filter(s -> s.length() > 5).count() > 2L) {
    // Yup...
}
like image 145
fge Avatar answered Feb 24 '23 10:02

fge