一:lambda作用:为了简化匿名内部类
函数式接口: 只有一个抽象方法的接口 @FunctionalInterface
可推导, 可省略
1.实现的接口和方法名, 省略
2.参数列表中的类型可以省略(如果只有一个参数, 小括号可以省略)
3.方法中只有一句代码, 大括号,return关键字,分号 可以省略
二:方法引用
双冒号 "::" 为引⽤运算符,⽽它所在的表达式被称为⽅法引⽤。如果Lambda要表达的函数⽅案已经存在于某个⽅法的实现中,那么则可以通过双冒号来引⽤该⽅法作为Lambda的替代
前提:
1.lambda表达式中只有一句代码 - 调用方法
2.lambda表达式的参数, 就是代码中调用的方法的参数
种类:
1.out.println(xx): 普通对象调用方法
例:
public class Demo03PrintOverload {
private static void printInteger(PrintableInteger data) {
data.print(1024);
}
public static void main(String[] args) {
printInteger(System.out::println);
}
}
等效表达式: ambda表达式: s -> System.out.println(s) -->⽅法引⽤:System.out::println
2.Math.abs(n): 类调用静态方法
@FunctionalInterface
public interface Calcable {//接口
int calc(int num);
}
public class Demo06MethodRef {
private static void method(int num, Calcable lambda) {
System.out.println(lambda.calc(num));
}
public static void main(String[] args) {
method(-10, Math::abs);
}
}
等效表达式:Lambda表达式: n -> Math.abs(n) --> ⽅法引⽤: Math::abs
3.this.m1(xx): this调用方法
@FunctionalInterface
public interface Richable {
void buy();
}
public class Husband {
private void buyHouse() {
System.out.println("买套房⼦");
}
private void marry(Richable lambda) {
lambda.buy();
}
public void beHappy() {
marry(() -> this.buyHouse());
}
}
等效表达式:Lambda表达式:() -> this.buyHouse() --> ⽅法引⽤:this::buyHouse
4.super.m2(xx): super调用方法
@FunctionalInterface
public interface Greetable {//接口
void greet();
}
//父类
public class Human {
public void sayHello() {
System.out.println("Hello!");
}
}
//子类
public class Man extends Human {
@Override
public void sayHello() {
System.out.println("⼤家好,我是Man!");
}
// 定义⽅法method,参数传递Greetable接⼝
public void method(Greetable g) {
g.greet();
}
public void show() {
method(super::sayHello);
}
}
等效表达式:Lambda表达式: () -> super.sayHello() --> ⽅法引⽤: super::sayHello
5.new Person(name): 调用构造方法 : 先构造一个简单的Person类,
public interface PersonBuilder {
Person buildPerson(String name);
}
public class Demo10ConstructorRef {
public static void printName(String name, PersonBuilder builder) {
System.out.println(builder.buildPerson(name).getName());
}
public static void main(String[] args) {
printName("赵丽颖", Person::new);
}
}
等效表达式:Lambda表达式: name -> new Person(name) --> ⽅法引⽤: Person::new
6.- new int[n]: 创建数组
@FunctionalInterface
public interface ArrayBuilder {
int[] buildArray(int length);
}
public class Demo12ArrayInitRef {
private static int[] initArray(int length, ArrayBuilder builder) {
return builder.buildArray(length);
}
public static void main(String[] args) {
int[] array = initArray(10, int[]::new);
}
}
等效表达式:Lambda表达式: length -> new int[length] -->⽅法引⽤: int[]::new
三:推导与省略
如果使⽤Lambda,那么根据“可推导就是可省略”的原则,⽆需指定参数类型,也⽆需指定的重
载形式 -- 它们都将被⾃动推导。⽽如果使⽤⽅法引⽤,也是同样可以根据上下⽂进⾏推导。
函数式接⼝是Lambda的基础,⽽⽅法引⽤是Lambda的孪⽣兄弟。