Java中的Lambda表达式

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);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值