Predicate.and()是Predicate接口的默认方法,用于函数式组合多个谓词使它们同时成立,支持链式调用和逻辑嵌套,提升过滤逻辑的可读性与复用性。

在 Java 中,Predicate.and() 是构建可读、可复用、声明式过滤逻辑的利器。它不是简单拼接条件,而是通过函数式组合让多个独立判断“同时成立”,天然支持链式调用和逻辑嵌套。
理解 Predicate.and() 的本质行为
and() 是 Predicate 接口的默认方法,签名是 default Predicate<t> and(Predicate super T> other)</t>。它返回一个新 Predicate,其 test() 行为等价于:当前谓词为 true 且传入的 other 谓词也为 true。即短路与(&&)的函数化封装。
关键点:
- 不修改原
Predicate,每次调用都生成新对象(不可变性) - 执行时从左到右,一旦左侧为 false 就跳过右侧(短路),提升效率
- 所有参与组合的
Predicate必须作用于同一类型T
基础链式组合:从单条件到多条件
直接链式调用 and() 是最直观的方式,适合条件数量适中、顺序明确的场景:
立即学习“Java免费学习笔记(深入)”;
Predicate<String> nonEmpty = s -> s != null && !s.trim().isEmpty(); Predicate<String> minLength3 = s -> s.length() >= 3; Predicate<String> containsDigit = s -> s.chars().anyMatch(Character::isDigit); Predicate<String> complexFilter = nonEmpty.and(minLength3).and(containsDigit); // 等价于:nonEmpty.test(s) && minLength3.test(s) && containsDigit.test(s)
这种写法清晰表达了“必须同时满足三个条件”,比嵌套 if 或冗长的 && 表达式更易维护。
结合方法引用与静态工厂,提升可读性与复用性
把常用条件提取为静态方法或常量,再用 and() 组装,能让业务逻辑更聚焦:
public class UserPredicates {
public static final Predicate<User> isActive = user -> user.isActive();
public static final Predicate<User> hasEmail = user -> user.getEmail() != null && user.getEmail().contains("@");
public static final Predicate<User> isAdult = user -> user.getAge() >= 18;
// 组合出“活跃的成年邮箱用户”
public static final Predicate<User> activeAdultWithEmail =
isActive.and(isAdult).and(hasEmail);
}
// 使用
List<User> candidates = users.stream()
.filter(UserPredicates.activeAdultWithEmail)
.collect(Collectors.toList());
这样定义后,activeAdultWithEmail 可被多处复用,且含义一目了然;后续若需调整某条规则(如邮箱校验加域名白名单),只需改对应常量,不影响组合逻辑。
动态组合与条件折叠:处理运行时不确定的过滤项
当过滤条件数量不固定(例如来自配置或用户选择),可用 Stream.reduce() 折叠多个 Predicate:
List<pre class="brush:php;toolbar:false;"dicate<Product>> filters = new ArrayList<>();
if (minPrice != null) filters.add(p -> p.getPrice() >= minPrice);
if (category != null) filters.add(p -> p.getCategory().equals(category));
if (inStock) filters.add(Product::isInStock);
Predicate<Product> combined = filters.stream()
.reduce(x -> true, Predicate::and); // 初始值为恒真谓词
List<Product> result = products.stream()
.filter(combined)
.collect(Collectors.toList());
注意:空列表时 reduce 返回恒真谓词(即不过滤),符合直觉。若需空列表时恒假,可改用 Optional.reduce() 并提供默认行为。
不复杂但容易忽略:and() 是组合工具,不是万能胶。它只表达“且”关系;要实现“或”,用 or();要取反,用 negate()。合理混用三者,才能写出真正灵活的过滤链。


















