1、基础介绍
当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用。
使用操作符 “ ::” 将方法名和对象或类的名字分隔开来。
Lambda 体中调用方法的参数列表与返回值类型要与函数式接口中抽象方法的函数列表和返回值类型保持一致。
若Lambda 参数列表中的第一个参数是实例方法的调用者,而第二个参数是实例方法的参数时,可以使用ClassName::method。
2、方法引用
2.1、类::静态方法名
@Test
public void test1(){
// 写法1:
Consumer<String> consumer = (x) -> System.out.print(x);
// 写法2:
PrintStream ps = System.out;
Consumer<String> con = ps::println;
// 写法3:
Consumer<String> con1 = System.out::println;
con1.accept("11");
}
2.2、类::静态方法名
@Test
public void test3(){
// 写法1:
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
// 写法2:
Comparator<Integer> com1 = Integer::compare;
Integer result = com1.compare(1, 2);
System.out.println(result);
}
2.3、类::实例方法名
@Test
public void test4(){
// 写法1:
BiPredicate<String, String> bp = (x, y) -> x.equals(y);
// 写法2:
BiPredicate<String, String> bp1 = String::equals;
boolean result = bp1.test("1", "1");
System.out.println(result);
}
BiPredicate<T, U>:函数式接口
参数:T,U;
返回类型:boolean;
包含方法为 boolean test(T t, U u);
3、构造器引用
需要调用的构造器的参数列表要与函数式接口中抽象方法的参数保持一致
Supplier<Student> sup1 = Student::new;
System.out.println(sup1.get());
Function<String, Student> fun = Student::new;
System.out.println(fun.apply("weiwei"));
BiFunction<String, Integer, Student> bf = Student::new;
System.out.println(bf.apply("weiwei", 2));
BiFunction<T, U, R>:函数式接口;
参数:T,U;
返回类型:R;
包含方法为 R apply(T t, U u);
4、数组引用
@Test
public void test6(){
// 写法1:
Function<Integer, Integer[]> fun = (x) -> new Integer[x];
System.out.println(fun.apply(2).length);
// 写法2:
Function<Integer, Integer[]> fun2 = Integer[]::new;
System.out.println(fun2.apply(3).length);
}