一、方法引用
当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
方法引用:使用操作符 “::” 将方法名和对象或类的名字分隔开来。
主要有三种语法形式
- 对象:: 实例方法名
- 类:: 静态方法名
- 类:: 实例方法名
1、demo
public class TestMethodRef {
//对象::实例方法名
@Test
public void test1(){
PrintStream ps = System.out;
Consumer<String> con = x -> ps.println(x);
PrintStream ps1 = System.out;
Consumer<String> con1 = ps1::println;
con1.accept("ssssbbbb");
}
@Test
public void test2(){
Employee employee = new Employee();
Supplier<String> sup = employee::getName;
String name = sup.get();
System.out.println(name);
}
//类:: 静态方法
@Test
public void test3(){
Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
Comparator<Integer> com1 = Integer::compare;
}
// 类::实例方法名
@Test
public void test4(){
BiPredicate<String,String> bp = (x,y) -> x.equals(y);
BiPredicate<String,String> bp2 = String::equals;
}
}
二、构造器引用
格式:className::new
注意:需要调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致
//构造器引用
@Test
public void test5(){
Supplier<Employee> sup = () -> new Employee();
Employee employee = sup.get();
//构造器引用的方式
// 根据函数式接口的参数列表来寻找对应的构造器,因为Supplier是无参的,此时调用无参构造器
Supplier<Employee> sup1 = Employee::new ;
System.out.println(sup1.get());
}
@Test
public void test6(){
//Employee::new 此时调用的构造器是一个参数的构造
Function<Integer,Employee> f = Employee::new;
Employee e = f.apply(24);
System.out.println(e.getAge());
BiFunction<Integer,String,Employee> bif = Employee::new;
Employee houchen = bif.apply(24, "houchen");
System.out.println(houchen);
}
三、数组引用
Type::new
//数组引用
@Test
public void test7(){
Function<Integer,String[]> f = (x) -> new String[x];
String[] strs = f.apply(10);
System.out.println(strs.length);
Function<Integer,String[]> fun2 = String[]::new;
String[] strs2 = fun2.apply(5);
System.out.println(strs2.length);
}