通过表达式来代替功能接口

形式

() -> {}
p1 -> {}
(p1, p2) -> {}

双冒号

t -> t.func()				等同于 	T::func
t -> C.func(t)				等同于 	C::func
() -> new T()				等同于	T::new
(p1, ...) -> new T(p1, ...)	等同于	T::new

单参数

定义一个接口

public interface Function<T, R> {
    R apply(T t);
}

定义一个类

@Data
public static class Student {
    private String name;
    private int age;
    
    public Student(String name) {
        this.name = name;
        this.age = 20;
    }
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

定义一个接口的实现

Function<Student, String> func = new Function<Student, String>() {
    @Override
    public String apply(Student student) {
        return student.getName();
    }
};

利用Function获取Studentname

Student student = new Student("Victor", 24);
String name = func.apply(student);

使用Lambda

Function<Student, String> func = student -> student.getName();
Function<Student, String> func = Student::getName;

可用于构造函数

Function<String, Student> func2 = new Function<String, Student>() {
    @Override
    public Student apply(String string) {
        return new Student(string);
    }
};

传入name生成Student

Student student = func2.apply("Victor");

使用Lambda

Function<String, Student> func2 = string -> new Student(string);
Function<String, Student> func2 = Student::new;

同理可得

Function<Integer, String[]> func3 = String[]::new;
String[] array = func3.apply(5);

多参数

定义一个接口

public interface BiFunction<T, U, R> {
    R apply(T t, U u);
}

同理可得

BiFunction<String, Integer, Student> biFun = Student::new;
Student student = biFun.apply("Victor", 24);

无参数

Runnable runnable = () -> System.out.println("Victor");
new Thread(runnable).start();