Lambda表达式的学习

Lambda表达式的使用前提

        1.有一个接口.

        2.接口中有且仅有一个抽象方法

Lambda表达式的格式

        格式:(形式参数)->{代码块}.

        形式参数:如果有多个参数,参数之间用逗号隔开;如果没有参数,括号中空着.

        ->:由英文中划线和大于符号组成,固定写法,代表指向动作.

        代码块:是具体想要做的事,就是方法体的内容.

public class Test2 {
    public static void main(String[] args) {
        test(()->{
            System.out.println("Lambda表达式");
        });
    }
    public static void test(InterA interA){
        interA.show();
    }
}

interface InterA{
    void show();

}

有参数无返回值

public class Test2 {
    public static void main(String[] args) {
        test((String a)->{
            System.out.println(a);
        });
    }
    public static void test(InterA interA){
        interA.show("有参数无返回值");
    }
}

interface InterA{
    void show(String a);
}

有返回值,无参数

public class Test2 {
    public static void main(String[] args) {
        test(()->{
            return 11;
        });
    }
    public static void test(InterA interA){
        int num=interA.show();
        System.out.println(num);
    }
}

interface InterA{
    int show();
}

注意:如果方法是有返回值的,在Lambda表达式中必须要有return,否则就会报错.

有参数,有返回值

public class Test2 {
    public static void main(String[] args) {
        test((int a,int b)->{
            return a+b;
        });
    }
    public static void test(InterA interA){
        int num=interA.show(1,1);
        System.out.println(num);
    }
}

interface InterA{
    int show(int a,int b);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值