就像名字一样,断言,它是一个值的断言,布尔值函数,它的任务很简单,给你一个true或false。
Predicate中进行断言的方法:
/*** Evaluates this predicate on the given argument.** @param t the input argument* @return {@code true} if the input argument matches the predicate,* otherwise {@code false}*/boolean test(T t);
其他方法可以创建与、或、非条件组合。
@Testpublic void predicateFi () {Predicate<String> xiaohundunPredicate = new Predicate<String>() {@Overridepublic boolean test (String o) {return o.contains("xiaohundun");}};Predicate<String> handsomePredicate = new Predicate<String>() {@Overridepublic boolean test (String o) {return o.contains("handsome");}};// negate方法复制此Predicate的‘非’(不handsome的Predicate =。=)handsomePredicate.negate().test("handsome");// false// Predicate的静态方法isEqual(Object tar)返回一个判断某对象是否与tar相等(使用Object#equals)的PredicateSystem.out.println(Predicate.isEqual(xiaohundunPredicate).test(handsomePredicate));// falseSystem.out.println(xiaohundunPredicate.test("xiaohundun"));// trueSystem.out.println(xiaohundunPredicate.and(handsomePredicate).test("xiaohundun hanhan"));// falseSystem.out.println(xiaohundunPredicate.or(handsomePredicate).test("xiaohundun hanhan"));// true}
Predicate Fi在流中的应用:
- Stream里边的filter、anyMatch、allMatch、noneMatch
Predicate Fi在非流中的应用:
- Collection里边的removeIf
- Optional里边的filter
- ObservableList(可以监听集合变化的集合)里边用到了Predicate
Predicate是一个参数的断言,还有两个参数的断言:BiPredicate,后者除了少了isEqual外其他都一样
