若Lambda体中的内容有方法已经实现了,我们可以使用"方法应用",可以理解为方法引用是Lambda表达式的另外一种表现形式。
使用操作符“::”将方法名和对象或类的名字分隔开
Consumer<String> consumer = (x) -> System.out.println(x);
等同于
Consumer<String> consumer = System.out::println;
BinaryOperator<Double> binaryOperator = (x, y) -> Math.pow(x, y);
等同于
BinaryOperator<Double> binaryOperator = Math::pow;
PS:
BiPredicate<String, String> biPredicate = (x, y) -> x.equals(y);
等同于
BiPredicate<String, String> biPredicate = String::equals;
PS:
格式: ClassName :: new
与函数式接口相结合,自动与函数式接口中方法兼容。
Function<String, Demo> supplier = (x) -> new Demo(x);
等同于
Function<String, Demo> supplier = Demo::new;
实体类方法:
class Demo{
Integer num;
String remark;
public Demo(String remark) {
this.remark = remark;
}
......
}
PS:需要调用的构造器的参数列表必须与函数式接口中抽象方法的参数列表保持一致。
格式: Type :: new
Function<Integer, String[]> function = (x) -> new String[x];
等同于
Function<Integer, String[]> function = String[] :: new;
原文:https://www.cnblogs.com/fx-blog/p/11744136.html