Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XOR in Java Lambda Expression for a List of boolean

Tags:

java

lambda

xor

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.

like image 495
froehli Avatar asked Dec 23 '22 18:12

froehli


1 Answers

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.

like image 147
Holger Avatar answered Dec 31 '22 15:12

Holger