Lambda相当于就是一个匿名方法,其在代替匿名内部类创建对象的时候,Lambda表达式代码块会代替实现抽象方法的方法体
Lambda表达式的目标类型必须是“函数式接口(FunctionalInterface)”。函数式接口只能包含一个抽象方法接口。函数式接口可以包含多个默认方法、类方法、但只能一个抽象方法
可以多个default关键字的抽象方法、类方法、变量
public class Lam {
@FunctionalInterface
interface Try{
Integer ss();
}
public static void main(String[] args) {
Try i=()->"sa".indexOf("a");
System.out.println(i.ss());
}
}Lambda的代码块中就是用来实现接口的抽象方法,而且有且只能有一个。若有default关键字的抽象方法是不属于函数式接口(FunctionalInterface) 存在@FunctionalInterface注解的一定是函数式接口,没有@FunctionalInterface不一定就不是函数式接口
public class Lam {
@FunctionalInterface
interface Try {
String s = "1";
Integer ss();
default Integer bb() {
return 0;
}
}
public static void main(String[] args) {
Try i = () -> "sa".indexOf("a");
System.out.println(i.s);
System.out.println(i.ss());
}
}种类 | 示例 | 说明 | 对应的Lambda表达式 |
|---|---|---|---|
引用类方法 | 类名::类方法 | 函数式接口中实现的方法的全部参数都传递给类方法作为参数 | (a,b,…)->类名.类方法(a,b,…) |
特定对象的实例方法 | 对象::实例方法 | 函数式接口中实现的方法的全部参数都传递给类方法作为参数 | (a,b,…)->对象.实例方法(a,b,…) |
引用某类对象的实例方法 | 类名::实例方法 | 函数式接口中实现的方法第一个参数作为调用者,之后的参数都作为方法的参数 | (a,b,…)->a.实例方法(b,…) |
引用构造方法 | 类名::new | 函数式接口中实现的方法的全部参数都传递给类方法作为参数 | (a,b,…)->类名.new(a,b,…) |
使用::这种方式,抽象方法肯定是存在参数的 其实上面三类可以归为一类来看待,这是形式不同而已
public class Lam {
@FunctionalInterface
interface Try {
String s = "1";
Integer ss(String s);
default Integer sb() {
return 0;
}
}
public static void main(String[] args) {
Try i = "sa"::indexOf;
System.out.println(i.s);
System.out.println(i.ss("a"));
}引用构造方法
public class Lam {
@FunctionalInterface
interface Try {
String s = "1";
String ss(String s);
default Integer sb() {
return 0;
}
}
public static void main(String[] args) {
Try i = String::new;
System.out.println(i.s);
System.out.println(i.ss("a"));
}等价于
public class Lam {
@FunctionalInterface
interface Try {
String s = "1";
String ss(String s);
default Integer sb() {
return 0;
}
}
public static void main(String[] args) {
Try i = new Try(){
@Override
public String ss(String s) {
return new String(s);
}
};
System.out.println(i.s);
System.out.println(i.ss("a"));
}同
异