Are there auxiliary classes that implement logical operations on Boolean collections in any of the standard libraries?

I came up with this little helper class and wanted to know if I could steal it somewhere, instead of reusing 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.

+4
source share
3 answers

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); } 
+11
source

While @ eng-fouad's answer is pretty good, I still suggest another that uses 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 a plus, I see:

  • Using the Guava Library
  • No need to write your own class using methods
  • Enhanced Readability (IMHO)
+2
source

I do not believe that there is any part of the Java Standard Libraries that provides exactly this functionality.

In some languages, they are provided as functions called anyOf (for or ) or allOf (for and ). You may be lucky to look for Java libraries that implement these functions.

Note. The code you are here can be optimized quite a bit. Note: if you compute AND from many booleans, once you find false , you can stop and say that the answer is false . Similarly, if you calculate the OR of booleans, you can stop as soon as you find true , since the answer will be true . This is essentially a generalization of a short circuit to lists of objects and the behavior of some versions of and and or in languages ​​like Scheme. This gives the following:

 public class ModifiedBooleans3 { private ModifiedBooleans3(){} public static boolean and(Iterable<Boolean> booleans) { for (Boolean boolRef : booleans) if (!boolRef) return false; return true; } public static boolean or(Iterable<Boolean> booleans) { for (Boolean boolRef : booleans) if (boolRef) return true; return false; } } 

Hope this helps!

+1
source

Source: https://habr.com/ru/post/1390011/


All Articles