lambda表达式
lambda表达式是jdk1.8的内容
必须是函数式接口才能使用。
函数式接口的定义是:
任何接口,如果只包含了一个抽象方法,那么就是函数式接口
interface Play{
void toplay();
}
lambda表达式是一步一步简化而来,正常来说,是在外部实现接口,创建对象来调用,即
//外部类
class Car implements Play{
@Override
public void toplay() {
System.out.println("开车");
}
}
public class Lambda {
public static void main(String[] args) {
Play car = new Car();
car.toplay();
}
}
然后还可以通过静态内部类
public class Lambda {
//静态内部类
static class Car implements Play{
@Override
public void toplay() {
System.out.println("开车");
}
}
public static void main(String[] args) {
Play car = new Car();
car.toplay();
}
}
还可以通过局部内部类
public class Lambda {
public static void main(String[] args) {
//局部内部类
class Car implements Play{
@Override
public void toplay() {
System.out.println("开车");
}
}
Play car = new Car();
car.toplay();
}
}
还可以通过匿名内部类
public class Lambda {
public static void main(String[] args) {
//匿名内部类
Play car = new Play() {
@Override
public void toplay() {
System.out.println("开车");
}
};
car.toplay();
}
}
然后还可以通过lambda表达式更加简洁
public class Lambda {
public static void main(String[] args) {
//lambda表达式
Play car = ()->{
System.out.println("开车");
};
car.toplay();
}
}
此时,还可以去掉花括号,更加简洁
public class Lambda {
public static void main(String[] args) {
//lambda表达式
Play car = ()->System.out.println("开车");
car.toplay();
}
}
如果,方法内有多条语句,要用花括号包起来
public class Lambda {
public static void main(String[] args) {
//lambda表达式
Play car = ()->{System.out.println("开车");
System.out.println("开车");}
car.toplay();
}
}
但函数式接口的方法有传参数时
interface Play{
void toplay(int a);
}
public class Lambda {
public static void main(String[] args) {
//lambda表达式
Play car = (int a) -> System.out.println("开车");
car.toplay();
}
}
也可以去掉a的参数类型
public class Lambda {
public static void main(String[] args) {
//lambda表达式
Play car = (a) -> System.out.println("开车");
car.toplay();
}
}
还能去掉a的括号
public class Lambda {
public static void main(String[] args) {
//lambda表达式
Play car = a -> System.out.println("开车");
car.toplay();
}
}
但是当有多个参数时,必须用括号包起来,要么两个参数类型写上,要么两个都不写
public class Lambda {
public static void main(String[] args) {
//lambda表达式
Play car = (a,b) -> System.out.println("开车");
car.toplay(1,1);
}
}
public class Lambda {
public static void main(String[] args) {
//lambda表达式
Play car = (int a,int b) -> System.out.println("开车");
car.toplay();
}
}