Lambda表达式

1、概念:
是匿名内部类的另外一种表现形式。
2、语法
(参数列表) -> {重写方法体};

3、无返回值,无参数的Lambda表达式

interface Inter4 {
    //无参数的无返回值的功能方法
    public void method();
}

public class Demo3_Lambda表达式 {

    public static void main(String[] args) {
        //匿名内部类(内部类实现接口)

        /*Inter4 inter4 = new Inter4() {
            @Override
            public void method() {
                System.out.println("内部类重写方法...");
            }  
        };*/
        Inter4 inter4 = () -> System.out.println("内部类重写方法");

        inter4.method();//内部类重写方法...

        //注意点:1、Lambda表达式式一般作用域内部类实现接口。
        //      2、Lambda表达式作用的接口,只能有一个方法。
        //      3、Lambda表达式作用的接口,只能又一个方法,该接口又称之功能式接口。
    }
}

4、带一个参数的,无返回值的Lambda表达式

interface Inter5 {

    //带1个参数无返回值的功能方法
    public void method(int i);
}

public class Demo3_Lambda表达式 {

    public static void main(String[] args) {

        Inter5 inter5 = x -> System.out.println(x * x);
        inter5.method(10);

        //注意点:如果Lambda表达式中的参数有且仅有一个时,小括号可以省略。
   }
}

5、多个参数无返回值的Lambda表达式

interface Inter6 {
    //带多个参数无返回值的功能方法
    public void method(int i, int j);
}

public class Demo3_Lambda表达式 {

    public static void main(String[] args) {

        Inter6 inter6 = (x, y) -> System.out.println(x + y);
        inter6.method(5, 2);

        //注意点:多个参数的Lambda表达式,小括号不能省略。
    }
}

6、多个参数有返回值的Lambda表达式

interface Inter7 {

    //带多个参数有返回值的功能方法
    public int method(int i, int j);
}

public class Demo3_Lambda表达式 {

    public static void main(String[] args) {

        Inter7 inter7 = (x, y) -> x + y;


        int method = inter7.method(7, 8);
        System.out.println(method);//15

        //注意1:如果方法体有且仅有一行代码时,大括号可以省略。
        //注意2:如果方法需要返回值,方法体有且仅有一行代码,该行代码的结果就是返回值,return可以省略。
    }
}

7、多个参数又返回值且方法体是多行代码的Lambda表达式

interface Inter8 {
    //方法体带多行代码的功能方法
    public int method(int i, int j);
}

public class Demo3_Lambda表达式 {

    public static void main(String[] args) {

        Inter8 inter8 = (x, y) -> {
            x *= x;
            return x + y;
        };
        int method = inter8.method(6, 2);
        System.out.println(method);//38

        //注意点1:如果方法体有多行代码,大括号不能省略。
        //注意点2:由于方法体有多行代码,所以返回值必须使用return返回
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值