流减少不兼容的类型 [英] stream reduction incompatible types
问题描述
我正在尝试创建一个包含多个谓词并减少它们的查找程序:
I'm trying to create a finder which takes several predicates and reduces them:
public static <T extends BusinessInterface> Collection<T> findOr(
Context pContext, Class<T> pClass, Predicate<? super T>... pPredicates) {
Predicate<? super T> lReducedPredicate =
Arrays.asList(pPredicates).stream().reduce(Predicate::or).orElse(r -> false);
return find(pContext, pClass, lReducedPredicate);
}
不幸的是我遇到以下编译错误:
Unfortunately I get following compiler error:
Predicate lReducedPredicate = Arrays.asList(pPredicates).stream()。reduce(Predicate :: or).orElse(r - > false);
不兼容类型:谓词不能转换为谓词
其中T是类型变量:
T扩展方法findOr中声明的BusinessInterface(Context,Class,Predicate ...)
其中CAP#1,CAP#2是新的类型变量:
CAP#1扩展Object super:T来自捕获?超级T
CAP#2扩展了Object super:T来自捕获? super T
Predicate lReducedPredicate = Arrays.asList(pPredicates).stream().reduce(Predicate::or).orElse(r -> false); incompatible types: Predicate cannot be converted to Predicate where T is a type-variable: T extends BusinessInterface declared in method findOr(Context,Class,Predicate...) where CAP#1,CAP#2 are fresh type-variables: CAP#1 extends Object super: T from capture of ? super T CAP#2 extends Object super: T from capture of ? super T
我在Eclipse中没有错误,我不知道出了什么问题。
I get not errors in Eclipse and I have no idea what is going wrong.
非常感谢任何帮助:)。
Any help is really appreciated :).
推荐答案
解决这个问题的一种方法是使用
One way to solve this is using
public static <T extends BusinessInterface> Collection<T> findOr(
Context pContext, Class<T> pClass, Predicate<? super T>... pPredicates) {
Predicate<? super T> lReducedPredicate = Arrays.asList(pPredicates).stream()
.reduce((a,b) -> t -> a.test(t) || b.test(t)).orElse(r -> false);
return find(pContext, pClass, lReducedPredicate);
}
虽然你不能调用或一个
谓词<?上的code>方法超级T>
实例与另一个谓词<?超级T>
作为参数,您可以创建相同的函数,或
将自己返回,因为传递 T
实例到 test
方法有效。
While you can’t invoke the or
method on a Predicate<? super T>
instance with another Predicate<? super T>
as argument, you can create the same function, or
would return, yourself, as passing a T
instance to either test
method is valid.
这篇关于流减少不兼容的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!