XOR in java lambda expression for list boolean

I started trying out Labda Expressions to implement Boolean-Gates for a Boolean props list. For "or" and "and" I wrote the following entries:

OR: expressions.stream().anyMatch(e -> e.evaluate(input));

AND: expressions.stream().allMatch(e -> e.evaluate(input));

e.evaluate(input)

returns true or false. But since there is no oneMatch allready method, I am stuck with XOR.

The first idea would be to filter out all true values ​​and check if it is just:

return expressions.stream().filter(e -> e.evaluate(input) == true).collect(Collectors.counting()) == 1;

      

But I would like to see this in one lambda expression.

+3


source to share


2 answers


If you want to know if there is exactly one match, you can use

expressions.stream().filter(e -> e.evaluate(input)).limit(2).count() == 1

      

limit(2)

avoids unnecessary processing, because once you encounter two matches, you already know that there cannot be a result ==1

, apart from other matches.



However, this is not "XOR" logic, not even remotely. If you want XOR operation you can use

expressions.stream().map(e -> e.evaluate(input)).reduce((a,b) -> a^b).orElse(Boolean.FALSE)

      

Unlike AND or OR, there is no way to short-circuit an XOR operation.

+6


source


I can't think of a lambda expression that suits your needs, but a little refactoring of your first idea looks good to me:



return expressions.stream().filter(e -> e.evaluate(input)).count() == 1;

      

+1


source







All Articles