Lambda表达式的使用前提
1.有一个接口.
2.接口中有且仅有一个抽象方法
Lambda表达式的格式
格式:(形式参数)->{代码块}.
形式参数:如果有多个参数,参数之间用逗号隔开;如果没有参数,括号中空着.
->:由英文中划线和大于符号组成,固定写法,代表指向动作.
代码块:是具体想要做的事,就是方法体的内容.
public class Test2 {
public static void main(String[] args) {
test(()->{
System.out.println("Lambda表达式");
});
}
public static void test(InterA interA){
interA.show();
}
}
interface InterA{
void show();
}
有参数无返回值
public class Test2 {
public static void main(String[] args) {
test((String a)->{
System.out.println(a);
});
}
public static void test(InterA interA){
interA.show("有参数无返回值");
}
}
interface InterA{
void show(String a);
}
有返回值,无参数
public class Test2 {
public static void main(String[] args) {
test(()->{
return 11;
});
}
public static void test(InterA interA){
int num=interA.show();
System.out.println(num);
}
}
interface InterA{
int show();
}
注意:如果方法是有返回值的,在Lambda表达式中必须要有return,否则就会报错.
有参数,有返回值
public class Test2 {
public static void main(String[] args) {
test((int a,int b)->{
return a+b;
});
}
public static void test(InterA interA){
int num=interA.show(1,1);
System.out.println(num);
}
}
interface InterA{
int show(int a,int b);
}