Lambda表达式

29 阅读2分钟

可以简化匿名内部类的代码量

只有接口有且只有一个抽象方法时才能用

语法格式:

()->重写方法的与具体;//无参无返回值
(参数1类型 参数1名字, 参数2类型 参数2名字...)->重写方法的语句体语句体;//有参无返回值
()->{语句体;return 值}//无参有返回值,{}可省略不写,return也可以省略
(参数1类型 参数1名字, 参数2类型 参数2名字...)->重写方法的语句体语句体;return 值;//有参有返回值

案例:

1.无参无返回值

package com.qf.c_lambda;
​
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();
    }
}
​

2.有参无返回值

package com.qf.c_lambda;
​
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);
    }
}
​

3.无参有返回值

package com.qf.c_lambda;
​
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());
​
    }
}
​

4.有参有返回值

package com.qf.c_lambda;
​
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);
    }
}
​