? 若Lambda体中的内容有方法已经实现了,我们可以使用“方法引用”。(可以理解为方法引用是Lambda表达式的另外一种表现形式)
主要有三种语法格式:
对象 :: 实例方法名
Consumer<String> consumer1 = (x) -> System.out.println(x);
consumer1.accept("fjh1");
PrintStream ps = System.out;
Consumer<String> consumer2 = ps::println;
consumer2.accept("fjh2");
类 :: 静态方法名
Comparator<Integer> comparator1 = (x,y) -> {
return Integer.compare(x,y);
};
Comparator<Integer> comparator2 = Integer::compare;
类 :: 实例方法名
参数列表中第一个参数是实例方法的调用者,第二个参数是实例方法的参数时,才可以使用这个语法。
BiPredicate<String,String> bp = (x,y)-> x.equals(y);
BiPredicate<String,String> bp2 = String::equals;
语法格式:类名 :: new
调用哪个构造器 取决于接口方法的参数,如本例的get()方法调用无参构造器,apply调用1参对应构造器。
Supplier<Animal> supplier1 = () -> new Animal();
Supplier<Animal> supplier2 = Animal::new;
System.out.println(supplier2.get());
Function<String,Animal> function1 = (x)-> new Animal(x);
Function<String,Animal> function2 = Animal::new;
System.out.println(function2.apply("fjh"));
语法格式:Type::new
Function<Integer,String[]> function = (x) -> new String[x];
String[] strs = function.apply(100);
System.out.println(strs.length);
Function<Integer,String[]> function2 = String[]::new;
String[] strs2 = function2.apply(200);
System.out.println(strs2.length);
原文:https://www.cnblogs.com/isfjh/p/15030583.html