Search code examples
javapredicate

How to xor predicates?


I need a method where I need to xor Predicates which I will recieve as method params. I have a somewhat working but cumbersome solution for two predicates. To give a simple, minimal and reproducible example:

Predicate<String> pred1  = s -> s.contains("foo");
Predicate<String> pred2  = s -> s.contains("bar");
    
String toTest = "foobar";

The logical OR will return true for given predicates and the test string:

boolean oneOnly   = pred1.or(pred2).test(toTest);

but for my use case it should return false since both substrings are included. It should only return true if and only if one condition is met.

For two prdeicates I have this

static boolean xor(Predicate<String> pred1, Predicate<String> pred2, String toTest){
    return pred1.and(pred2.negate()).or(pred2.and(pred1.negate())).test(toTest);
}

Is there a simple but a convinient way to xor predicates?


Solution

  • In followup to @xdhmoore's answer, that's overkill and can be done much simpler:

    static <T> Predicate<T> xor(Predicate<T> pred1, Predicate<T> pred2) {
        return t -> pred1.test(t) ^ pred2.test(t);
    }