1、方法引用
当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
方法引用可以看做是Lambda表达式深层次的表达。换句话说,方法引用就是Lambda表达式,也就是函数式接口的一个实例,通过方法的名字来指向一个方法,可以认为是Lambda表达式的一个语法糖。
要求:实现接口的抽象方法的参数列表和返回值类型,必须与方法引用的方法的参数列表和返回值类型保持一致!
格式:使用操作符“::” 将类(或对象) 与方法名分隔开来。
如下三种主要使用情况:
- 对象::实例方法名
- 类::静态方法名
- 类::实例方法名
(1) 对象的引用::实例方法
public class FunCall_01 {
public static void main(String[] args) {
Integer i1 = new Integer(12356);
// 常规lambda表达式
// 使用供应商接口,不需要参数
// 返回字符串
Supplier<String> su = () -> i1.toString();
System.out.println(su.get());
// 方法引用的写法
Supplier<String> su1 = i1::toString;
System.out.println(su1.get());
}
}
(2) 类名::静态方法名
public class FunCall_02 {
public static void main(String[] args) {
// 常规的lambda写法
// 前两个是 参数类型,第三个是返回值类型
BiFunction<Integer, Integer, Integer> bif = (x,y) -> Integer.max(x, y);
int apply = bif.apply(10, 11);
System.out.println(apply);
// 方法引用的写法
BiFunction<Integer, Integer, Integer> bif1 = Integer::max;
int apply1 = bif1.apply(19, 2);
System.out.println(apply1);
}
}
(3) 类名::实例方法
public class FunCall_03 {
public static void main(String[] args) {
// 传统的lambda写法
// 两个字符串类型参数 x,y, 返回boolean
BiPredicate<String, String> predicate = (x,y) -> x.equals(y);
System.out.println(predicate.test("a", "c"));
// 方法引用写法
BiPredicate<String, String> predicate1 = String::equals;
System.out.println(predicate1.test("a", "a"));
}
}
2 构造器引用:
格式:ClassName::new
与函数式接口相结合,自动与函数式接口中方法兼容。
可以把构造器引用赋值给定义的方法,要求构造器参数列表要与接口中抽象方法的参数列表一致!且方法的返回值即为构造器对应类的对象。
public static void main(String[] args) {
// 无参构造器
// 常规的lambda写法
// 供应商接口,没有参数,供应 Object 类型
Supplier<Object> objSup = ()-> new Object();
System.out.println(objSup.get());
// 方法引用
Supplier<Object> objSup1 = Object::new;
System.out.println(objSup1.get());
// 有参构造器
// 常规的lambda写法
// 参数是字符串,返回值是整数
Function<String, Integer> func = x -> new Integer(x);
System.out.println(func.apply("123"));
// 方法引用写法
Function<String, Integer> func1 = Integer::new;
System.out.println(func1.apply("54"));
}
3 数组引用
比如,定义一个Integer类型的数组,长度为n。
public static void main(String[] args) {
// lambda写法
// 参数是数组长度,返回值是 Integer类型的数组
Function<Integer, Integer[]> fun = n -> new Integer[n];
//传入 10 ,创建长度为10的数组
Integer[] arr = fun.apply(10);
System.out.println(arr.length);//10
// 数组引用写法
Function<Integer, Integer[]> fun1 = Integer[]::new;
Integer[] arr1 = fun1.apply(2);
System.out.println(arr1.length);
}