方法引用: 若 Lambda 体中的内容有方法已经实现了,我们可以使用“方法引用”(可以理解方法引用是 Lambda 表达式的另外一种表现形式)
三种语法格式:
对象::实例方法名
Lambda 体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数列表和返回值类型保持一致。
@Test
public void test1() {
// 写法一:
Consumer<String> con1 = (x) -> System.out.println(x);
// 写法二:
// 创建 PrintStream 的实例对象 out
// 在 PrintStream 类中 println() 是其实例方法
PrintStream out = System.out;
Consumer<String> con2 = out::println;
// 写法三:将创建实例和方法引用写到一起
Consumer<String> con3 = System.out::println;
con3.accept("Java8 方法引用");
// Lambda 体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数列表和返回值类型保持一致。
}
@Test
public void test2() {
// Lambda 体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数列表和返回值类型保持一致。
/*
employee.getName(); 方法中不需要参数,返回值为 String 类型
Supplier 接口中的抽象方法不需要参数,返回值类型为 T, T get();
Supplier<String> sup = () -> employee.getName();
此时指定了 泛型为 String 类型, get() 返回值的类型为 String,
此时可以写成函数引用的形式
Supplier<String> sup = employee::getName;
*/
Employee employee = new Employee("Tom", 18, 15000.0);
Supplier<String> sup = () -> employee.getName();
String str = sup.get();
System.out.println(str);
Supplier<Integer> sup2 = employee::getAge;
Integer age = sup2.get();
System.out.println(age);
}
类::静态方法名
Lambda 参数列表中的第一个参数是实例方法的调用者,第二个参数是实例方法的参数,可以使用 ClassName::method
@Test
public void test4() {
BiPredicate<String, String> bp = (x, y) -> x.equals(y);
BiPredicate<String, String> bp2 = String::equals;
}
类::实例方法名
@Test
public void test3() {
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
Comparator<Integer> com1 = Integer::compare;
}
构造方法引用:
格式:ClassName::new
注意:调用的构造器的参数列表与函数式接口中的抽象方法的参数列表保持一致!
public class Employee {
private String name;
private Integer age;
private Double salary;
public Employee() {}
public Employee(String name) {
this.name = name;
}
public Employee(String name, Integer age, Double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
@Test
public void test5() {
Supplier<Employee> sup = () -> new Employee();
// 构造方法引用
Supplier<Employee> sup2 = Employee::new;
Employee employee = sup2.get();
System.out.println(employee);
Function<String, Employee> fun = (x)->new Employee(x);
Function<String, Employee> fun2 = Employee::new;
Employee smith = fun2.apply("Smith");
System.out.println(smith);
}
数组引用
格式:Type::new;
@Test
public void test6() {
Function<Integer, String[]> fun = (x)->new String[x];
String[] strArr = fun.apply(10);
System.out.println(strArr.length);
Function<Integer, String[]> fun2 = String[]::new;
String[] strArr2 = fun.apply(5);
System.out.println(strArr2.length);
}