java - 如何正确组合谓词过滤器?

标签 java java-stream

我想创建在一个谓词中组合 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/

相关文章:

java - 创建计划任务,在指定时间后执行

java - Java 14 记录文档中 "shallowly immutable"的含义

java - 使用请求调度程序 JSP 发送 404

java - 在java中展平一个嵌套的N级嵌套对象

java - 从另一个对象列表中删除重复的列表对象值

java - 使用事件监听器作为 Java 8 Stream 源

java - 为什么 java 有 int 和 int Integer 数据类型,我可以将数据从一个数据类型移动到另一个数据类型吗?

Java 8 : get average of more than one attribute

Java流: How to find id from json?

java - 手机无法连接到同一 wifi 网络上的 Flask 服务器