Java8新特性-Lambda表达式

总结一下java8中的新特性 lambda表达式

Lambda是一个匿名函数,可以理解为一段可以传递的代码(将代码像数据一样传递);可以写出更简洁、更灵活的代码;作为一种更紧凑的代码风格,是Java语言表达能力得到提升。

有一个需求: 获取公司中年龄小于 35 的员工信息获取公司中工资大于 5000 的员工信息

public class Employee {

    private int id;
    private String name;
    private int age;
    private double salary;
    // get/set/constructor...

}
List emps = Arrays.asList(
    new Employee(101, "张三", 18, 9999.99),
    new Employee(102, "李四", 59, 6666.66),
    new Employee(103, "王五", 28, 3333.33),
    new Employee(104, "赵六", 8, 7777.77),
    new Employee(105, "田七", 38, 5555.55)
);

该需求最直接的实现方式,遍历筛选符合条件的员工

// 获取小于 35 的员工信息
public List filterEmployeeAge(List emps){
    List list = new ArrayList<>();

    for (Employee emp : emps) {
        if(emp.getAge()  filterEmployeeSalary(List emps){
        List list = new ArrayList<>();

        for (Employee emp : emps) {
            if(emp.getSalary() >= 5000){
                list.add(emp);
            }
        }

        return list;
    }

如果又增加一种筛选条件,岂不是又要增加一个方法,且很多代码都是重复的,我们来进行优化

优化方式一:策略模式改造

// 抽象接口
public interface MyPredicate {
    public boolean test(T t);
}
// 按年龄筛选策略类
public class FilterEmployeeForAge implements MyPredicate{

    @Override
    public boolean test(Employee t) {
        return t.getAge()  {
    @Override
    public boolean test(Employee t) {
        return t.getSalary() >= 5000;
    }
}
//优化方式一:策略设计模式
@Test
public void test4(){
    List list = filterEmployee(emps, new FilterEmployeeForAge());
    // 获取小于 35 的员工信息
    for (Employee employee : list) {
        System.out.println(employee);
    }

    System.out.println("------------------------------------------");
    // 获取工资大于5000的员工信息
    List list2 = filterEmployee(emps, new FilterEmployeeForSalary());
    for (Employee employee : list2) {
        System.out.println(employee);
    }
}
public List filterEmployee(List emps, MyPredicate mp){
    List list = new ArrayList<>();

    for (Employee employee : emps) {
        if(mp.test(employee)){
            list.add(employee);
        }
    }

    return list;
}

优化方式二:匿名内部类

//优化方式二:匿名内部类
@Test
public void test5(){
    List list = filterEmployee(emps, new MyPredicate() {
        @Override
        public boolean test(Employee t) {
            return t.getId()

优化方式三:Lambda 表达式

//优化方式三:Lambda 表达式
@Test
public void test6(){
    List list = filterEmployee(emps, (e) -> e.getAge()  list2 = filterEmployee(emps, (e) -> e.getSalary() >= 5000);
    list2.forEach(System.out::println);
}

优化方式四:Stream API

Stream API也是java8的新特性,为了保持这个例子的完整性,我也还是放在了这里,可以跳过,在了解完 Stream API可以再回来看这个简单例子

@Test
public void test7(){
    emps.stream()
        .filter((e) -> e.getAge()

从上面的演变过程如下:

&#x5783;&#x573E;&#x4EE3;&#x7801; --> &#x7B56;&#x7565;&#x6A21;&#x5F0F; --> &#x533F;&#x540D;&#x5185;&#x90E8;&#x7C7B; --> Lambda&#x8868;&#x8FBE;&#x5F0F; --> Stream API

可以看出,lambda没有一句废话,直奔主题(我们的筛选条件),为我们减少了很多工作量

那么lambda语法如何使用呢?

// 1.无参数,无返回值
@Test
public void test01(){
    Runnable runnable = () -> {
        System.out.println("Hello Lambda");
    };
}
// 2.有一个参数,无返回值
@Test
public void test02(){
    Consumer consumer = (a) -> System.out.println(a);
    consumer.accept("我觉得还行!");
}
// 3.有一个参数,无返回值 (小括号可以省略不写)
@Test
public void test03(){
    Consumer consumer = a -> System.out.println(a);
    consumer.accept("我觉得还行!");
}
// 4。有两个及以上的参数,有返回值,并且 Lambda 体中有多条语句
@Test
public void test04(){
    Comparator comparator = (a, b) -> {
        System.out.println("比较接口");
        return Integer.compare(a, b);
    };
}
// 5.有两个及以上的参数,有返回值,并且 Lambda 体中只有1条语句 (大括号 与 return 都可以省略不写)
@Test
public void test05(){
    Comparator comparator = (a, b) -> Integer.compare(a, b);
}

Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即”类型推断”: (Integer a, Integer b) -> Integer.compare(a, b);

函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。

函数式接口可以被隐式转换为 lambda 表达式。

MyFun接口是一个函数式接口,它接受一个输入Integer参数 num,返回一个Integer结果。

使用@FunctionalInterface将这个接口定义为函数式接口

// 增加@FunctionalInterface注解
@FunctionalInterface
public interface MyFun {
    public Integer getValue(Integer num);
}

需求:对一个数进行运算

//需求:对一个数进行运算
@Test
public void test6(){
    Integer num = operation(100, (x) -> x * x);
    System.out.println(num);

    System.out.println(operation(200, (y) -> y + 200));
}

public Integer operation(Integer num, MyFun mf){
    return mf.getValue(num);
}

Original: https://www.cnblogs.com/mrxccc/p/16504727.html
Author: 狮子挽歌丿
Title: Java8新特性-Lambda表达式

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/588666/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球