Lambda表达式之方法引用和构造器引用
一.方法引用
方法引用:若Lambda 体中的内容有方法已经有实现了,我们可以使用“方法引用”(可以理解为方法引用是Lambda 表达式的另一种表现形式 )
主要的三种语法
1.对象::实例方法名
// 对象:: 实例方法名
@Test
public void test1(){
// 消费型接口 传入一个参数 无返回值
Consumer<String> con = (x) -> System.out.println(x);
//方法引用
Consumer<String> con1 = System.out::println;
con1.accept("ajihuh");
}
@Test
public void test2(){
Employee emp = new Employee();
Supplier<String> sup = () -> emp.getName();
String s = sup.get();
System.out.println(s);
// 方法引用
Supplier<Integer> sup2 = emp::getAge;
System.out.println(sup.get());
}
2.类名::静态方法名
@Test
public void test3(){
Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
// compare 静态方法
Comparator<Integer> com1 = Integer::compare;
}
3.类名:: 实例方法名
@Test
public void test4(){
BiPredicate<String, String> bp = (x, y) -> x.equals(y);
BiPredicate<String, String> bp1 = String::equals;
}
注意
①Lambda 体中调用方法的参数列表与返回值类型,要与函数式接口中的函数列表和返回值类型保持一致。
②若Lambda 表达式有两个参数,第一个参数是实例方法的调用者,而第二个参数是实例方法的参数时,可以使用类名::实例方法
构造器引用
格式:
类名:: new
@Test
public void test5(){
Supplier<Employee> sup = () -> new Employee();
Supplier<Employee> sup2 = Employee::new;
Employee employee = sup.get();
System.out.println(employee);
}
@Test
public void test6(){
Function<Integer, Employee> fun = (x) -> new Employee(x);
Employee employee = fun.apply(10);
System.out.println(employee);
Function<Integer, Employee> fun2 = Employee::new;
Employee employee1 = fun2.apply(100);
System.out.println(employee1);
}
注意
需要调用的构造器的参数列表要与函数式接口中的抽象方法的参数列表保持一致!
三.数组引用
格式;
type[ ]::new;
@Test
public void test7(){
Function<Integer, String[]> fun = (x) -> new String[x];
String[] strings = fun.apply(10);
System.out.println(strings.length);
Function<Integer, String[]> fun2 = String[]::new;
String[] strings1 = fun2.apply(20);
System.out.println(strings1.length);
}