I started to try out Labda Expressions for implementing Boolean-Gates for a list of boolean input paramter. For "or" and "and" I wrote the following statments:
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 onceMatch method allready implemented I am stuck with the XOR.
First idea would be to filter all true values and check if it is just one:
return expressions.stream().filter(e -> e.evaluate(input) == true).collect(Collectors.counting()) == 1;
But I would like to see it in one lambda expression.
If you want to know whether there is exactly one match, you can use
expressions.stream().filter(e -> e.evaluate(input)).limit(2).count() == 1
the limit(2)
avoids unnecessary processing, as once you encountered two matches, you already know that the result can’t be ==1
, without needing to count the other matches.
However, that’s not “XOR” logic, not even remotely. If you want an XOR operation, you may 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.
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