Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 317
ripper234 Avatar asked Dec 06 '22 17:12

ripper234


2 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);
}
like image 138
Eng.Fouad Avatar answered Dec 09 '22 05:12

Eng.Fouad


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:

  • Uses Guava library
  • No need to write own class with methods
  • Better readability (IMHO)
like image 27
Slava Semushin Avatar answered Dec 09 '22 06:12

Slava Semushin