Lamda表达式的方法引用
在使用Lamda表达式的过程中已经感受到它的便捷,但是在例子中的输出语句还在使用System.out.println()方法进行输出,但是它还符合消费型接口,那么能否更简便的使用呢,现在它来了,也就是方法引用。
方法引用
方法引用的两个注意事项
- Lamda体中调用方法的参数列表、返回值类型与方法的参数列表、返回值类型一致(这里的方法指的是要方法引用的方法)。
- Lamda表达式第一个参数为方法的调用者,第二个参数为方法的参数,可以使用类::实例方法名
方法引用类型
- 类名::实例方法名
- 类名::静态方法名
- 对象名::实例方法名
对象名::实例方法名
@Test
public void test1(){
Consumer<String> con = (x) -> System.out.println(x);
PrintStream ps = System.out;
Consumer<String> con1 = ps::println;
Consumer<String> con2 = System.out::println();
}
类名::静态方法名
@Test
public void test3() {
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
com.compare(30, 9);
Comparator<Integer> com1 = Integer::compareTo;
com1.compare(20, 90);
}
类名::实例方法名
这一格式的前提就是注意事项第二条。
@Test
public void test4() {
BiPredicate<String, String> bp = (x, y) -> x.equals(y);
BiPredicate<String, String> bp2 = String::equals;
}
构造器引用
构造器引用与方法引用一样,前提是构造器的参数列表与Lamda表达式的参数列表一致。
@Test
public void test5() {
Supplier<Employee> sup = () -> new Employee();
// 构造器引用
Supplier<Employee> sup2 = Employee::new;
}
数组引用
就是简单的数据类型+[]::new;
@Test
public void test7() {
Function<Integer, String[]> fun = (x) -> new String[x];
String[] strs = fun.apply(10);
System.out.println(strs.length);
Function<Integer, String[]> fun2 = String[]::new;
String[] apply = fun2.apply(20);
System.out.println(apply.length);
}