我需要一个方法,其中我需要,xor,谓词,我将收到它作为方法参数。对于两个谓词,我有一个有点工作但很麻烦的解决方案。为了给出一个简单的、最小的、可重复的例子:
Predicate<String> pred1 = s -> s.contains("foo");
Predicate<String> pred2 = s -> s.contains("bar");
String toTest = "foobar";逻辑或将返回给定谓词和测试字符串的true:
boolean oneOnly = pred1.or(pred2).test(toTest);但是对于我的用例,它应该返回false,因为这两个子字符串都包括在内。只有在满足了一个条件的情况下,它才应该返回true。
我有两笔钱
static boolean xor(Predicate<String> pred1, Predicate<String> pred2, String toTest){
return pred1.and(pred2.negate()).or(pred2.and(pred1.negate())).test(toTest);
}是否有一种简单但方便的方法来进行xor谓词?
发布于 2021-04-25 21:25:26
作为@xdhmoore答案的后续,这是过火的,可以做得更简单:
static <T> Predicate<T> xor(Predicate<T> pred1, Predicate<T> pred2) {
return t -> pred1.test(t) ^ pred2.test(t);
}发布于 2021-04-25 21:24:19
更新:
下面是一些例子,说明为什么您希望返回谓词而不是布尔值,但是@rzwitserloot的answer做得很好,而且更简洁。
扮演魔鬼的提倡者:它不那么漂亮,但是对于你已经拥有的方式来说,它的一个优势是你稍微更符合谓语成语。稍微调整一下会让你:
返回谓词
static <T> Predicate<T> xor(Predicate<T> pred1, Predicate<T> pred2){
return pred1.and(pred2.negate())
.or(pred2.and(pred1.negate()));
}
// Which means you can do this, which is probably more conducive to combining your
// new xor function with other predicates:
xor((Integer a) -> a > 1, (Integer b) -> b < 10).test(0));
// For example, because you return a Predicate:
xor((Integer a) -> a > 1, (Integer b) -> b < 10).negate().test(0));返回布尔值
static <T> boolean xor(Predicate<T> pred1, Predicate<T> pred2, T toTest) {
return pred1.test(toTest) ^ pred2.test(toTest);
}
// In contrast, if your xor function returns a boolean, you get this, which is
// similar, but is less conducive to using all the Predicate methods:
xor((Integer a) -> a > 1, (Integer b) -> b < 10, 14);
// To be honest, this seems more readable to me than the negate() function in the
// example above, but perhaps there are scenarios where the above is preferred...
!xor((Integer a) -> a > 1, (Integer b) -> b < 10, 14)没什么大不了的,但你的问题让我好奇.
发布于 2021-04-25 21:36:54
您可以使用stream.reduce将xor‘’ed谓词还原为单个谓词,然后返回结果。
就像这样:
import java.util.function.Predicate;
import java.util.Arrays;
public class MultiXor{
public static void main(String[] args){
System.out.println(xor("monkey", p -> p.equals("monkey"), p -> p.equals("dork"), p -> p.equalsIgnoreCase("Monkey")) );
System.out.println(true ^ false ^ true);
System.out.println(xor("monkey", p -> p.equals("monkey"), p -> p.equals("dork")) );
System.out.println(true ^ false);
}
public static <T> boolean xor(final T param, Predicate<T>... predicates){
return Arrays.stream(predicates).reduce( p -> false, (previous, p) -> r -> previous.test(param) ^ (p.test(param))).test(param);
}}
https://stackoverflow.com/questions/67258123
复制相似问题