Java方法引用
方法引用通过方法的名字来指向一个方法,可以使语言的构造更紧凑,减少冗余代码。
1.使用情境:
当要传递给lambda体的操作,已经有实现的方法了,就可以使用方法引用。
2.方法引用的本质:
本质上就是lambda表达式,而lambda表达式作为函数接口的实例,所以方法引用,也是函数接口的
实例。
3.使用格式: 类(或对象) :: 方法名
4.具体分为如下的三种情况.
4.1对象 :: 非静态方法
//情况一:对象::实例方法
//Consumer中void accept(T t)
//PrintStream中的void println(T t)
@Test
public void test2(){
//lambda表达式形式
Consumer<String> con1 = str -> System.out.println(str);
con1.accept("I love you.");//I love you.
System.out.println("**************");
//方法引用
PrintStream ps = System.out;
Consumer<String> con2 = ps::println;
con2.accept("I love you always.");//I love you always.
}
4.2类 :: 静态方法
//情况二:类::静态方法
//Comparator中的int compare(T t1,T t2)
//Integer中int compare(T t1,T t2)
@Test
public void test3(){
Comparator<Integer> com1 = (t1,t2) -> Integer.compare(t1,t2);
System.out.println(com1.compare(22,31));//-1
System.out.println("*************");
Comparator<Integer> com2 = Integer::compare;
System.out.println(com2.compare(22,31));//-1
}
4.3类 :: 非静态方法
//情况三:类::实例方法
//Comparator中的int compare(T t1, T t2)
//String中int t1.compareTo(t2)
@Test
public void test4(){
Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2);
System.out.println(com1.compare("like","love"));//-6
Comparator<String> com2 = String::compareTo;
System.out.println(com2.compare("yy","hh"));//17
}
5.方法引用使用的要求:要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的形参列表和返回值类型完全相同。
7.构造器引用:函数式接口的抽象方法的形参列表和构造器的形参列表一致,抽象方法的返回值类型即为构造器所属类的类型。
6.数组引用:可以把数组看作式一个特殊的类,则写法与构造器引用相同。
//数组引用
//Function中的R apply(T t)
@Test
public void test6(){
Function<Integer, String[]> func1 = Length -> new String[Length];
String[] arr1 = func1.apply(3);
System.out.println(Arrays.toString(arr1));//[null, null, null]
Function<Integer,String[]> func2 = String[] :: new;
String[] arr2 = func2.apply(5);
System.out.println(Arrays.toString(arr2));//[null, null, null, null, null]
}