Lambda 表达式
lambda表达式的类型是函数,但是在Java中,Lambda表达式是对象,必须依附于对象类型—函数式接口(Function Interface)
JDK8主要内置lambda 函数式接口
-
Consumer::accept 一个参数无返回
1
2void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after) // 后面执行的行为 -
Function::apply 一个参数有返回
1
2
3R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) // bef执行结果返回为行为的参数
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) // 行为结果为aft的参数 -
BiFunction::apply 二个参数有返回
1
2R apply(T t, U u);
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after)// 行为结果为aft的参数 -
Predicate::test 一个参数返回布尔
1
2
3
4boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) // 并且
default Predicate<T> negate() // 取反
default Predicate<T> or(Predicate<? super T> other) // 或者 -
Supplier::get 无参数有返回
1
T get();
1
2Supplier<Object> supplier2 = Object::new;
public Object() {} // new 实际使用的是无参构造方法
lambda实例
1 |
System.out::println; |
函数式接口
@FunctionalInterface
关于函数式接口:
- 如果一个接口只有一个抽象方法(除Object的override方法|默认方法和静态方法不会破坏函数式接口的定义),那么接口就是一个函数式接口。
- 如果我们在一个接口上声明了FunctionalInterface注解,那么编译器就会按照函数式接口的定义来要求该接口。
- 如果某个接口只有一个抽象方法,但我们并没有给该接口声明FunctionalInterface注解,那么编译器依旧会将该接口看作是函数式接口。
1 |
// 函数式接口 |
定义函数式接口
1 |
public interface MyParentInterface { |