简介
在Java8中为现在有的函数能够友好的使用Lambda表达式,因此引入了函数式接口,其中一个接口仅有一个抽象方法的普通接口。如果声明多个抽象方法则会报错,但是默认方法和静态方法在接口中可以定义多个
声明接口为函数式接口,需要在接口上添加@FunctionalInterface注解
样例:
- 声明函数式接口
@FunctionalInterface
public interface MyFunctionalInterface {
void execute();
}
- 使用
public class FunctionalInterfaceDemo {
public static void demo(MyFunctionalInterface myFunctionalInterface) {
myFunctionalInterface.execute();
}
public static void main(String[] args) {
//jdk8之前
demo(new MyFunctionalInterface() {
@Override
public void execute() {
System.out.println("jdk8之前实现");
}
});
//jdk8之后
demo(() -> System.out.println("jdk8之后实现"));
}
}
类库常见使用函数接口
在Java8的类库设计中定义了非常多的函数式接口,比较常用的几个函数式接口:Predicate、Consumer、Function、Supplier
Predicate使用
Predicate接口是Java8定义的一个函数式接口,属于java.util.function包下,用于进行判断操作,内部定义一个抽象方法test、三个默认方法and,negate,or、一个静态方法isEqual
源码
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicate<T> negate() {
return (t