I concocted this little helper class, and wanted to know if there's anywhere I can steal it from instead of re-implementing the wheel:
public class Booleans3 {
private Booleans3(){}
public static boolean and(Iterable<Boolean> booleans) {
boolean result = true;
for (Boolean boolRef : booleans) {
boolean bool = boolRef;
result &= bool;
}
return result;
}
public static boolean or(Iterable<Boolean> booleans) {
boolean result = false;
for (Boolean boolRef : booleans) {
boolean bool = boolRef;
result |= bool;
}
return result;
}
}
I looked at com.google.common.primitives.Booleans, and it doesn't seem to contain what I need.
How about this:
public static boolean and(Collection<Boolean> booleans)
{
return !booleans.contains(Boolean.FALSE);
}
public static boolean or(Collection<Boolean> booleans)
{
return booleans.contains(Boolean.TRUE);
}
While @eng-fouad answer is good enough I still suggest another one which utilizes Iterables.all() and Iterables.any() with equalTo predicate:
import java.util.Arrays;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static com.google.common.collect.Iterables.all;
import static com.google.common.collect.Iterables.any;
import static com.google.common.base.Predicates.equalTo;
...
Iterable<Boolean> booleans = Arrays.asList(TRUE, TRUE, FALSE);
System.out.println(all(booleans, equalTo(TRUE)));
System.out.println(any(booleans, equalTo(TRUE)));
will print
false
true
As pluses I see:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With