gpt4 book ai didi

java - 是否可以使用不同的类型参数将谓词与 `and` 链接起来?

转载 作者:行者123 更新时间:2023-12-04 08:49:49 24 4
gpt4 key购买 nike

我正在学习 Java 8 lambda。我可以在 Predicate 接口(interface)中加入两个具有不同类型参数的谓词,使用和方法吗?
这是我的代码:

Predicate<Integer> pc = (iv) -> iv > 20;
Predicate<String> pL = (is) -> is.length() > 5;
System.out.println("The predicate result for pc is: " + pc.test(25));
System.out.println("===========");
System.out.println("The predicate result with both condition true: " + pc.and(pL.test("abcd")));

最佳答案

不,您不能链接不同类型的谓词,除非链接的谓词也接受原始谓词的类型。
查看签名,您可以很容易地看到:and(Predicate<? super T> other)or(Predicate<? super T> other)您可以链接谓词:

Predicate<Person> isMale = p -> p.isMale();
Predicate<Person> isAdult = p -> p.age() >= AGE_OF_MATURITY;
Predicate<Person> isAdultMale = isAdult.and(isMale);
您只能链接至少接受与原始谓词相同类型的谓词(这就是 ? super T 所说的):
Predicate<Object> hasWeirdHashCode = o -> o.hashCode() == 0;
Predicate<Person> nonsense = isMale.and(hasWeirdHashCode);
如果要测试不同的类型( AB ),则需要分别提供:
Predicate<A> propertyOfA = [...];
Predicate<B> propertyOfB = [...];

BiPredicate<A,B> propertyOfAnB = (a, b) ->
propertyOfA.test(a) && propertyOfB.test(b);
如果您需要两种以上不同的类型,则需要滚动您自己的自定义 TriPredicate , QuadPredicate等等功能接口(interface),应该可以直接实现。

关于java - 是否可以使用不同的类型参数将谓词与 `and` 链接起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64148667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com