[英]How to correctly combine the predicates filter?
I want to create method for combine Predicate::and in one predicate and submit it on input list.我想在一个谓词中创建组合 Predicate::and 的方法并将其提交到输入列表中。 I have code:
我有代码:
public static List<?> getFilteredList(Collection<?> collection, Collection<Predicate<?>> filters) {
return collection.stream()
.filter(filters.stream().reduce(Predicate::and).orElse(t -> true))
.collect(Collectors.toList());
}
But compiler says that there is a error in Predicate::and
Incompatible types: Predicate<capture of?> is not convertible to Predicate<? super capture of?>
但是编译器说
Predicate::and
Incompatible types: Predicate<capture of?> is not convertible to Predicate<? super capture of?>
Incompatible types: Predicate<capture of?> is not convertible to Predicate<? super capture of?>
How to fix it?如何解决?
As it stands, you could be providing completely incompatible predicates:就目前而言,您可能会提供完全不兼容的谓词:
Collection<Predicate<?>> predicates =
List.of((String s) -> s.isEmpty(), (Integer i) -> i >= 0)
Combining those doesn't make sense.把这些结合起来没有意义。
You need to provide predicates which are compatible with the collection
elements:您需要提供与
collection
元素兼容的谓词:
public static <T> List<T> getFilteredList(
Collection<? extends T> collection,
Collection<? extends Predicate<? super T>> predicates) {
Predicate<T> combined = predicates.stream().reduce(t -> true, Predicate::and, Predicate::and);
return collection.stream()
.filter(combined)
.collect(Collectors.toList());
}
I went to town a bit on the wildcards here.我在这里的通配符上去了城镇。 You could do it in a much simpler way, at the expense of flexibility in the arguments it will accept:
您可以以一种更简单的方式来完成它,但会牺牲 arguments 的灵活性,它将接受:
public static <T> List<T> getFilteredList(
Collection<T> collection,
Collection<Predicate<T>> predicates) {
Predicate<T> combined = predicates.stream().reduce(t -> true, Predicate::and);
return collection.stream()
.filter(combined)
.collect(Collectors.toList());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.