Java 如何正确组合谓词过滤器?
我想在一个谓词中为combine Predicate::and创建方法,并将其提交到输入列表中。我有密码:Java 如何正确组合谓词过滤器?,java,java-stream,Java,Java Stream,我想在一个谓词中为combine Predicate::and创建方法,并将其提交到输入列表中。我有密码: public static List<?> getFilteredList(Collection<?> collection, Collection<Predicate<?>> filters) { return collection.stream() .filter(filters.stream().redu
public static List<?> getFilteredList(Collection<?> collection, Collection<Predicate<?>> filters) {
return collection.stream()
.filter(filters.stream().reduce(Predicate::and).orElse(t -> true))
.collect(Collectors.toList());
}
publicstaticlist getFilteredList(Collection-Collection,Collection目前,您可能提供了完全不兼容的谓词:
Collection<Predicate<?>> predicates =
List.of((String s) -> s.isEmpty(), (Integer i) -> i >= 0)
我在这里谈到了一些通配符。你可以用一种更简单的方法来做,但要牺牲它所能接受的论点的灵活性:
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());
}
公共静态列表getFilteredList(
收藏,
集合谓词){
谓词组合=谓词.stream().reduce(t->true,谓词::and);
return collection.stream()
.过滤器(组合式)
.collect(Collectors.toList());
}
您试图利用签名列表getFilteredList(收集,收集)有什么用
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());
}