[英]How to correctly combine the predicates filter?
我想在一個謂詞中創建組合 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?>
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)
把這些結合起來沒有意義。
您需要提供與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());
}
我在這里的通配符上去了城鎮。 您可以以一種更簡單的方式來完成它,但會犧牲 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.