目录
1 方法引用
用方法引用改进代码
双冒号 :: 写法,这被称为“方法引用”,而双冒号是一种新的语法
双冒号 :: 为引用运算符,而它所在的表达式被称为方法引用。如果Lambda要表达的函数方案已经存在于某个方法的实现中,那么则可以通过双冒号来引用该方法作为Lambda的替代者
列:实现方法引用
创建函数是接口
@FunctionalInterface
public interface Printable {
public abstract void myPrint(String str);
}
public class Demo01Printable {
//定义一个方法,参数传递Printable接口,对字符串进行打印
public static void method(Printable printable) {
printable.myPrint("hello");
}
public static void main(String[] args) {
//调用printString方法,方法的参数Printable是一个函数式接口,所以可以传递Lambda
method(str -> System.out.println(str));
/*
分析:
Lambda表达式的目的,打印参数传递的字符串
把参数s,传递给了System.out对象,调用out对象中的方法println对字符串进行了输出
注意:
1.System.out对象是已经存在的
2.println方法也是已经存在的
所以我们可以使用方法引用来优化Lambda表达式
可以使用System.out方法直接引用(调用)println方法
*/
method(System.out::println);
}
}
方法引用:通过对象名引用成员方法
这是最常见的一种用法,与上例相同。如果一个类中已经存在了一个成员方法
public interface AInterface {
void aInterfaceMethod(String str);
}
public class A {
public void methodA(String str){
System.out.println(str);
}
}
public class B {
// 接口作为方法的参数
public static void method(AInterface aInterface){
aInterface.aInterfaceMethod(&