就像名字一样,断言,它是一个值的断言,布尔值函数,它的任务很简单,给你一个true或false。

    Predicate中进行断言的方法:

    1. /**
    2. * Evaluates this predicate on the given argument.
    3. *
    4. * @param t the input argument
    5. * @return {@code true} if the input argument matches the predicate,
    6. * otherwise {@code false}
    7. */
    8. boolean test(T t);

    其他方法可以创建与、或、非条件组合。

    1. @Test
    2. public void predicateFi () {
    3. Predicate<String> xiaohundunPredicate = new Predicate<String>() {
    4. @Override
    5. public boolean test (String o) {
    6. return o.contains("xiaohundun");
    7. }
    8. };
    9. Predicate<String> handsomePredicate = new Predicate<String>() {
    10. @Override
    11. public boolean test (String o) {
    12. return o.contains("handsome");
    13. }
    14. };
    15. // negate方法复制此Predicate的‘非’(不handsome的Predicate =。=)
    16. handsomePredicate.negate().test("handsome");// false
    17. // Predicate的静态方法isEqual(Object tar)返回一个判断某对象是否与tar相等(使用Object#equals)的Predicate
    18. System.out.println(Predicate.isEqual(xiaohundunPredicate).test(handsomePredicate));// false
    19. System.out.println(xiaohundunPredicate.test("xiaohundun"));// true
    20. System.out.println(xiaohundunPredicate.and(handsomePredicate).test("xiaohundun hanhan"));// false
    21. System.out.println(xiaohundunPredicate.or(handsomePredicate).test("xiaohundun hanhan"));// true
    22. }

    Predicate Fi在流中的应用:

    • Stream里边的filter、anyMatch、allMatch、noneMatch

    Predicate Fi在非流中的应用:

    • Collection里边的removeIf
    • Optional里边的filter
    • ObservableList(可以监听集合变化的集合)里边用到了Predicate

    Predicate是一个参数的断言,还有两个参数的断言:BiPredicate,后者除了少了isEqual外其他都一样