Java8新特性-Lambda表达式笔记

本文介绍了Lambda表达式的概念、基本语法,并展示了如何用它优化Java代码,特别是通过接口MyPredicate实现年龄和工资筛选。重点讲解了Lambda表达式在接口中的应用和其在简化代码上的优势。
摘要由CSDN通过智能技术生成

Lambda表达式是一个匿名函数,一段可以传递的代码(将代码像数据一样进行传递)

//匿名内部类实现接口
@Test
public void test1() {
    Comparator<Integer> com = new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return Integer.compare(o1, o2);
        }
    };

    //传递com
    TreeSet<Integer> treeSet = new TreeSet<>(com);
}
//Lambda表达式
@Test
public void test2() {
    Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
    //传递com
    TreeSet<Integer> treeSet = new TreeSet<>(com);
}

1.需求:获取当前公司中员工年龄大于35的员工信息。2.需求:获取当前公司中员工工资大于3500的员工信息

if (employee.getAge() >= 35) {
    emps.add(employee);
}

如上代码是一般方法,每次改变if中的条件进行筛选,但是比较冗余。

优化方式一,创建接口,用类来实现接口以便实现筛选的功能。

public interface MyPredicate<T> {
    public boolean test(T t);
} 

优化方式二,使用匿名内部类

public void test3() {
    List<Employee> employees1 = filterEmployees1(employees, new MyPredicate<Employee>() {
        @Override
        public boolean test(Employee employee) {
            return employee.getSalary() <= 5000;
        }
    });

    for (Employee employee : employees1) {
        System.out.println(employee);
    }
}

优化方式三,使用Lambda表达式

public void test4() {
    List<Employee> employees1 = filterEmployees1(employees, (e) -> e.getSalary() <= 5000);

    for (Employee employee : employees1) {
        System.out.println(employee);
    }
}

第二部分:Lambda表达式基本语法

箭头操作符将Lambda表达式拆分为两部分,左侧为表达式的参数列表,右侧为表达式需要执行的功能

参数对应接口中抽象方法的参数,如图所示。

语法格式一:无参数,无返回值

() -> System.out.println("Hello Lambda");
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("hello world");
    }
};

Runnable runnable1 = () -> System.out.println("hello world");
runnable1.run();

语法格式二:有一个参数,无返回值

Consumer<String> consumer = (x) -> System.out.println(x);//consumer接口中的accept方法有一个参数,右侧的lambda表达式对接口进行了实现.

语法格式三:有两个以上参数,有返回值,Lambda体有多条语句 

Comparator<Integer> comparator = (x, y) -> {
    System.out.println("函数式接口");
    return Integer.compare(x, y);  
};

语法格式四:有两个以上参数,有返回值,Lambda体只有一条语句 

Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);

Lambda表达式需要函数式接口的支持

函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值