Lambda 表达式

Lambda 表达式

lambda表达式的类型是函数,但是在Java中,Lambda表达式是对象,必须依附于对象类型—函数式接口(Function Interface)

JDK8主要内置lambda 函数式接口

  • Consumer::accept 一个参数无返回

    1
    2
    void accept(T t);
    default Consumer<T> andThen(Consumer<? super T> after) // 后面执行的行为
  • Function::apply 一个参数有返回

    1
    2
    3
    R 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
    2
    R apply(T t, U u);
    default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after)// 行为结果为aft的参数
  • Predicate::test 一个参数返回布尔

    1
    2
    3
    4
    boolean 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
    2
    Supplier<Object> supplier2 = Object::new;
    public Object() {} // new 实际使用的是无参构造方法

lambda实例

1
System.out::println;

函数式接口

@FunctionalInterface

关于函数式接口:

  1. 如果一个接口只有一个抽象方法(除Object的override方法|默认方法和静态方法不会破坏函数式接口的定义),那么接口就是一个函数式接口。
  2. 如果我们在一个接口上声明了FunctionalInterface注解,那么编译器就会按照函数式接口的定义来要求该接口。
  3. 如果某个接口只有一个抽象方法,但我们并没有给该接口声明FunctionalInterface注解,那么编译器依旧会将该接口看作是函数式接口。
1
2
3
4
5
// 函数式接口
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface {}

定义函数式接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public interface MyParentInterface {
void test();
}

@FunctionalInterface
public interface MyInterface extends MyParentInterface {
void test();
String toString(); // ☑️ override Object
default void defaultMethod() { }// ☑️ 可以使用默认方法
static void staticMethod() {} // ☑️ 可以使用静态方法
}

// 实例
// 编译的时候str会被编译为final
// final String str = "";
String str = "---";
MyInterface myInterface = () -> {
System.out.println("Hello" + str);
};
 上一篇