Lambda表达式的使用:
1,格式:
->:lambda操作符或箭头操作符
左边:lambda形参列表(其实就是接口中的抽象方法的形参列表)
右边:lambda体(其实就是重写的抽象方法的方法体)
2,本质:
作为函数式接口的实例
3,如果一个接口中,只声明了一个抽象方法,则此方法就称为函数式接口
我们可以在一个接口上使用:@FunctionalInterface注解
这样可以检查它是否是一个函数式接口
6种语法 例子:
public class LambdaTest{
@Test
public void test(){
//第一种:无参,无返回值
Runnable r1=()->{
System.out.println("hello1");
};
r1.run();
//第二种:有参,无返回值
InterfaceTest interfaceTest=(str)->{
System.out.println(str);
};
interfaceTest.stringOutput("hello2");
//第三种:若只有一个参数的时候,参数小括号可以省略
InterfaceTest test= str ->{
System.out.println(str);
};
test.stringOutput("hello3");
//第四种:有两个或两个以上参数,且有返回值
AddInterface addInterface=(a,b)->{
int c=a+b;
return c;
};
System.out.println(addInterface.add(10, 20));
//第五种:Lambda体当只有一条语句时,return和大括号可以省略
AddInterface addInterface1=(a,b)->a+b;
System.out.println(addInterface.add(10, 20));
}
}
interface InterfaceTest{
public void stringOutput(String str);
}
interface AddInterface{
int add(int a,int b);
}