lambda表达式被称为闭包。函数式编程,就是为了简化代码,让代码更加简洁。
Lambda表达式的语法格式
函数式接口,接口下面有且只有有一个抽象类,才能使用Lambada
接口 接口对象 = ()->表达式; 无参无返回值的
接口 接口对象 = (parameter)->表达式; 有参无返回值的
接口 接口对象 = ()->{表达式;} 无参有返回值的
接口 接口对象 = (parameter)->{表达式;} 有参有返回值的
无参无返回值的
interface Computer {
void coding();
}
public class Demo2 {
public static void main(String[] args) {
//接口 接口对象 = ()->表达式;
Computer computer = ()-> System.out.println("荞麦大");
//test(()-> System.out.println("嗷嗷叫的敲代码"));
test(computer);
test(()-> System.out.println("荞麦大"));
test(new Computer() {
@Override
public void coding() {
System.out.println("嘻嘻敲打吗");
}
});
}
public static void test (Computer computer) {
computer.coding();
}
}
有参无返回值
interface A {
//有参无返回值的方法
void eat (String name, int age);
}
public class Demo3 {
public static void main(String[] args) {
test(new A() {
@Override
public void eat(String name, int age) {
System.out.println(name+ "年龄为:" + age + ",在吃牛肉");
}
}, "狗蛋", 12);
//把 方法中的接口 变成了lambada表达式
//接口 接口对象 = (parameter)->表达式; 有参无返回值的
test((name, age)-> System.out.println(name+ "年龄为:" + age + ",在吃牛肉"), "呵呵", 89);
}
public static void test (A a, String name, int age) {
a.eat(name, age);
}
}
无参有返回值
接口 接口对象 = ()->{表达式;} 无参有返回值的
interface B {
int num();
}
public class Demo4 {
public static void main(String[] args) {
test(new B() {
@Override
public int num() {
return 50;
}
});
test(()->{return 50;});
}
public static void test (B b) {
System.out.println(b.num());
}
}
有参有返回值
interface C {
int add(int a, int b);
}
public class Demo5 {
public static void main(String[] args) {
//->前面是 啥? 是方法 带小括号的 方法的名字可以省略
//->后面是 啥? 抽象方法的方法体实现的代码
test((a, b) -> a + b, 4, 5);
}
public static void test(C c, int a, int b) {
int sum = c.add(a, b);
System.out.println(sum);
}
}