1.1常用函数式接口:
1.1.1 Predicate函数式接口:
- Predicate函数式接口概述:用来封装判断条件。
- Predicate函数式接口的抽象方法:boolean test(T t) 执行判断。返回true或false
需求:定义方法,参数是Predicate接口类型,返回值是Boolean类型,在main方法调用定义好的方法判断字符串的长度是否大于5.
import java.util.function.Predicate;
public class PredicateDemo {
public static void main(String[] args) {
//使用匿名内部类
testPredicate(new Predicate<String>() {
@Override
public boolean test(String s) {
return s.length()>5;
}
});
//使用Lambda表达式调用
testPredicate(str->str.length()>5);
}
public static void testPredicate(Predicate<String> predicate){
boolean b = predicate.test("Hello");
System.out.println("b="+b);
}
}
1.1.2 默认方法:and(等价&&)
- 既然是条件判断,就会存在与、或、非三种常见的逻辑关系。其中将两个Predicate条件使用“与”逻辑连接起来实现“并且”的效果时,可以使用default方法and。其JDK源码为&