我想创建在一个谓词中组合 Predicate::and 的方法并将其提交到输入列表上。我有代码:
public static List<?> getFilteredList(Collection<?> collection, Collection<Predicate<?>> filters) {
return collection.stream()
.filter(filters.stream().reduce(Predicate::and).orElse(t -> true))
.collect(Collectors.toList());
}
但是编译器说 Predicate::and
有错误Incompatible types: Predicate<capture of ?> is not convertible to Predicate<? super capture of ?>
如何解决?
最佳答案
就目前情况而言,您可能会提供完全不兼容的谓词:
Collection<Predicate<?>> predicates =
List.of((String s) -> s.isEmpty(), (Integer i) -> i >= 0)
将这些结合起来没有意义。
您需要提供与集合
元素兼容的谓词:
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());
}
我在这里用通配符进城了一下。您可以用更简单的方式来做到这一点,但代价是它接受的参数的灵活性:
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());
}
关于java - 如何正确组合谓词过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62795266/