java8新特性之lambda表达式

lambda表达式优化了匿名内部类的书写 减少了代码的冗余

函数式接口 定义:

1.在接口中只能有一个抽象方法  

2.@FunctionalInterface 标记为函数式接口

3.通过default修饰为普通方法

4.可以定义object的方法

lambda的基础语法:

()---  参数列表

  ->        分隔符

  { }        方法体

例子:

1)无参方法调用

package com.sypm.service;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Wang
 * @Date: 2024/04/07/22:00
 * @Description:
 */
@FunctionalInterface
public interface Example1Interface {
    void get();
}
package com.sypm.service;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Wang
 * @Date: 2024/04/07/22:03
 * @Description:
 */
public class Test01 {
    public static void main(String[] args) {
        //匿名内部类
        new Example1Interface() {
            @Override
            public void get() {
                System.out.println("get");
            }
        }.get();
        //lambda表达式
        Example1Interface example1Interface = ()->{
            System.out.println("使用了lambda表达式的写法");
        };
        example1Interface.get();
    }
}

2)有参方法调用

package com.sypm.service;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Wang
 * @Date: 2024/04/07/22:15
 * @Description:
 */
public interface Example2Interface {
    String get(int a,int b);
}
package com.sypm.service;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Wang
 * @Date: 2024/04/07/22:16
 * @Description:
 */
public class Test02 {
    public static void main(String[] args) {
        //匿名内部类调用
        Example2Interface example2Interface = new Example2Interface() {
            @Override
            public String get(int a, int b) {
                return a + "---" + b;
            }
        };
        System.out.println(example2Interface.get(2, 5));
        //改为lambda表达式
        Example2Interface example2Interface1 = (a,b)->{
            return a + "---" + b;
        };
        System.out.println(example2Interface1.get(3, 4));
    }
}

lambda表达式的简化:

package com.sypm.service;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Wang
 * @Date: 2024/04/07/22:32
 * @Description:
 */
public class Test03 {
    public static void main(String[] args) {
        Example1Interface example1Interface = () -> {
            System.out.println("使用了lambda表达式的写法");
        };
        example1Interface.get();

        //简化 基本语法骨架-->加括号包起来-->强转为指定类型-->调用方法
        ((Example1Interface) () -> {
            System.out.println("使用了lambda表达式的写法");
        }).get();
    }
}

待补充.......................

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值