在 Java 中,Predicate(断言) 是 java.util.function 包下的一个函数式接口,常用于条件判断,典型场景是过滤(filter)。
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
Predicate<Integer> isPositive = x -> x > 0;
System.out.println(isPositive.test(5)); // true
System.out.println(isPositive.test(-3)); // false
List<Integer> list = List.of(1, 2, 3, 4, 5, 6);
List<Integer> result = list.stream()
.filter(n -> n % 2 == 0)
.toList();
System.out.println(result); // [2, 4, 6]
Predicate<Integer> gt10 = x -> x > 10;
Predicate<Integer> lt20 = x -> x < 20;
Predicate<Integer> between = gt10.and(lt20);
System.out.println(between.test(15)); // true
Predicate<String> startA = s -> s.startsWith("A");
Predicate<String> endZ = s -> s.endsWith("Z");
Predicate<String> condition = startA.or(endZ);
System.out.println(condition.test("Apple")); // true
Predicate<Integer> isEven = x -> x % 2 == 0;
Predicate<Integer> isOdd = isEven.negate();
System.out.println(isOdd.test(3)); // true
public static <T> List<T> filter(List<T> list, Predicate<T> predicate) {
List<T> result = new ArrayList<>();
for (T t : list) {
if (predicate.test(t)) {
result.add(t);
}
}
return result;
}
使用:
List<String> names = List.of("Tom", "Alice", "Bob");
List<String> result = filter(names, s -> s.length() > 3);
✅ 集合过滤
✅ 校验规则(如参数校验)
✅ 条件分支抽象
✅ 规则引擎
✅ Stream / Optional
// 传统写法
if (x > 0) { ... }
// Predicate 写法(更灵活、可复用)
Predicate<Integer> p = x -> x > 0;
if (p.test(x)) { ... }
如果你是想了解 Spring 中的断言(Assert) 或 JUnit 的断言,也可以告诉我,我可以分别讲。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。