1. @Test
  2. public void test02(){
  3. // Lambda 表达式
  4. Comparator<Integer> comparator = (a, b) -> Integer.compare(a, b);
  5. TreeSet<Integer> set = new TreeSet<>(comparator);
  6. }

演变过程:
- 垃圾代码 —> 策略模式 —> 匿名内部类 —> Lambda表达式
口诀:

  • 写死小括号,拷贝右箭头,落地大括号
  • 左右遇一括号省
  • 左侧推断类型省

左侧:抽象方法的形参;右侧:具体实现类的方法

1.lambda表达式的基础语法:

Java8中引入了一个新的操作符”->”,该操作符称为箭头操作符或者lambda操作符,箭头操作符将lambda表达式拆分成两部分:
左侧:lambda表达式的参数列表
右侧:lambda表达式中所需执行的功能,即lambda体。

2.语法格式:

1.无参数,无返回值

()->System.out.println(“Hello Lambda!”);

  1. @Test
  2. public void test1() {
  3. int num = 0;//jdk1.7前,必须是final,但实质还是 final修饰
  4. Runnable r1 = new Runnable() {
  5. @Override
  6. public void run() {
  7. System.out.println("Hello World!" + num);
  8. }
  9. };
  10. r1.run();
  11. System.out.println("---------------------------------------");
  12. Runnable r2 = () -> System.out.println("Hello Lambda!");
  13. r2.run();
  14. }

2.有一个参数,无返回值

  1. @Test
  2. public void test2() {
  3. Consumer<String> consumer = (x) -> System.out.println(x);
  4. consumer.accept("我是家里蹲毕业!");
  5. }

3.若只有一个参数,小括号可以省略不写

  1. @Test
  2. public void test2() {
  3. Consumer<String> consumer = x -> System.out.println(x);
  4. consumer.accept("我是家里蹲毕业!");
  5. }

4.有两个以上的参数,有返回值,并且lambda体中有多条语句

  1. @Test
  2. public void test3() {
  3. Comparator<Integer> comparator = (x, y) -> {
  4. System.out.println("函数式接口");
  5. return Integer.compare(x, y);
  6. };
  7. System.out.println(comparator.compare(1, 3));
  8. }

5.若lambda体中只有一条语句,return和大括号都可以省略不写

  1. @Test
  2. public void test4() {
  3. Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
  4. System.out.println(comparator.compare(1, 3));
  5. }

6.lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出数据类型,即“类型推断”

3.lambda表达式需要函数式接口的支持:

函数式接口:
接口中只有一个抽象方法的接口,称为函数式接口。可以使用注解@FunctionalIterface修饰一下,可以检查是否为函数式接口。
2.测试:

  1. @FunctionalInterface
  2. public interface MyFun {
  3. public Integer getValue(Integer integer);
  4. }
  5. public Integer operation(Integer num, MyFun mf) {
  6. return mf.getValue(num);
  7. }
  8. @Test
  9. public void test6() {
  10. Integer operation = operation(100, (x) -> x * 2);
  11. System.out.println(operation);
  12. }

4.lambda案例

  • 1.调用 Collections.sort() 方法,通过定制排序 比较两个 Employee (先按照年龄比,年龄相同按照姓名比),使用 Lambda 表达式作为参数传递

    1. //员工集合
    2. List<Employee> employeeList = Arrays.asList(
    3. new Employee("张三", 18, 6669.58),
    4. new Employee("李四", 12, 7779.58),
    5. new Employee("王五", 36, 9229.58),
    6. new Employee("赵六", 51, 19999.58),
    7. new Employee("田七", 20, 3399.58)
    8. );
    9. @Test
    10. public void test1() {
    11. Collections.sort(employeeList, (e1, e2) -> {
    12. if (e1.getAge() == e2.getAge()) {
    13. return e1.getName().compareTo(e2.getName());
    14. } else {
    15. return Integer.compare(e1.getAge(), e2.getAge());
    16. }
    17. });
    18. for (Employee employee : employeeList) {
    19. System.out.println(employee);
    20. }
    21. }
  • 2.声明函数式接口,接口中声明抽象方法,String getValue(String str); 声明类 TestLambda,类中编写方法使用接口作为参数,将一个字符串转换成大写,并作为方法的返回值;再将一个字符串的第二个和第四个索引位置进行截取字串

    1. @FunctionalInterface
    2. public interface MyFunction {
    3. public String getValue(String string);
    4. }
    5. public String strHandler(String string, MyFunction mf) {
    6. return mf.getValue(string);
    7. }
    8. @Test
    9. public void test2() {
    10. System.out.println(strHandler("sjdsjdka", (x) -> x.toUpperCase()));
    11. System.out.println(strHandler("sjdsjdka", (x) -> x.substring(2, 4)));
    12. }
  • 3.声明一个带两个泛型的函数式接口,泛型类型为 T 为参数,R 为返回值;接口中声明对应的抽象方法;在 TestLambda 类中声明方法,使用接口作为参数,计算两个 Long 类型参数的和;在计算两个 Long 类型参数的乘积

    1. @FunctionalInterface
    2. public interface MyFunction<T, R> {
    3. public R getValue(T t1, T t2);
    4. }
    5. public void getHandler(Long l1, Long l2, MyFunction<Long, Long> mf) {
    6. System.out.println(mf.getValue(l1, l2));
    7. }
    8. @Test
    9. public void test3() {
    10. getHandler(30L, 20L, (x, y) -> x + y);
    11. getHandler(30L, 20L, (x, y) -> x * y);
    12. }

    5.函数式接口

    | 函数式接口 | 参数类型 | 返回类型 | 用途 | | —- | —- | —- | —- | | Consumer
    消费型接口 | T | void | 对类型为T的对象应用操作:void accept(T t) | | Supplier
    提供型接口 | 无 | T | 返回类型为T的对象:T get() | | Function
    函数型接口 | T | R | 对类型为T的对象应用操作,并返回结果为R类型的对象:R apply(T t) | | Predicate
    断言型接口 | T | boolean | 确定类型为T的对象是否满足某约束,并返回boolean值:boolean test(T t) |

1.Consumer:消费型接口 void accept(T t);

  1. @Test
  2. public void test() {
  3. happy(30000, (x) -> System.out.println("你们刚哥喜欢大保健,每次消费:" + x + "元"));
  4. }
  5. public void happy(double money, Consumer<Double> consumer) {
  6. consumer.accept(money);
  7. }

2.Supplier:提供型接口 T get();

  1. @Test
  2. public void test1() {
  3. System.out.println(getNumList(10, () -> (int) (Math.random() * 100)));
  4. }
  5. //随机产生指定个数的整数,并放入集合中
  6. public List<Integer> getNumList(int num, Supplier<Integer> supplier) {
  7. List<Integer> list = new ArrayList<>();
  8. for (int i = 0; i < num; i++) {
  9. Integer integer = supplier.get();
  10. list.add(integer);
  11. }
  12. return list;
  13. }

3.Function:函数型接口 R apply(T t);

  1. @Test
  2. public void test3() {
  3. System.out.println(strHandler("jalasjd", (x) -> x.toUpperCase()));
  4. }
  5. //需求:用于处理字符串
  6. public String strHandler(String string, Function<String, String> function) {
  7. return function.apply(string);
  8. }

4.Predicate:断言型接口 boolean test(T t);

  1. @Test
  2. public void test4() {
  3. List<String> list = Arrays.asList("2112", "2123123", "3423432", "435345");
  4. System.out.println(filterStr(list, (x) -> x.contains("2")));
  5. }
  6. //断言型接口
  7. public List<String> filterStr(List<String> list, Predicate<String> predicate) {
  8. List<String> returnList = new ArrayList<>();
  9. for (int i = 0; i < list.size(); i++) {
  10. if (predicate.test(list.get(i))) {
  11. returnList.add(list.get(i));
  12. }
  13. }
  14. return returnList;
  15. }

5.其他接口

image.png

6.方法引用和构造器引用

1.方法引用:

若Lambda体中的内容有方法已经实现了,我们可以使用 “方法引用”(可以理解为方法引用是Lambda表达式的另外一种表现形式)

主要有三种语法格式:

1.对象::实例方法名
  1. @Test
  2. public void test1() {
  3. Consumer<String> consumer = x -> System.out.println(x);
  4. PrintStream printStream = System.out;
  5. Consumer<String> consumer1 = printStream::println;
  6. Consumer<String> consumer2 = System.out::println;
  7. consumer2.accept("atguigu NB");
  8. }
  9. @Test
  10. public void test2() {
  11. Employee employee = new Employee();
  12. Supplier<String> supplier = () -> employee.getName();
  13. System.out.println(supplier.get());
  14. Supplier<Integer> supplier1 = employee::getAge;
  15. System.out.println(supplier1.get());
  16. }

注意:
  • Lambda体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数列表和返回值类型保持一致。
    2.类::静态方法名
    1. @Test
    2. public void test3() {
    3. Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
    4. Comparator<Integer> comparator1 = Integer::compare;
    5. comparator1.compare(3, 5);
    6. }
    3.类::实例方法名
    1. @Test
    2. public void test4() {
    3. BiPredicate<String, String> biPredicate = (x, y) -> x.equals(y);
    4. BiPredicate<String, String> biPredicate1 = String::equals;
    5. System.out.println(biPredicate1.test("hahaha", "hahah"));
    6. }
    注意:
  • 若Lambda参数列表中的第一个参数是实例方法的调用者,而第二个参数是实例方法的参数时,可以使用ClassName::method

    2.构造器引用:

    格式:ClassName::new

    1. @Test
    2. public void test5() {
    3. Supplier<Employee> supplier = () -> new Employee("ha", 20, 30);
    4. Employee employee = supplier.get();
    5. System.out.println(employee);
    6. Supplier<Employee> supplier1 = Employee::new;
    7. Employee employee1 = supplier1.get();
    8. System.out.println(employee1);
    9. }
    10. @Test
    11. public void test6() {
    12. Function<Integer, Employee> function = (x) -> new Employee(x);
    13. System.out.println(function.apply(20));
    14. Function<Integer, Employee> function1 = Employee::new;
    15. System.out.println(function1.apply(20));
    16. }

    注意:
  • 需要调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致。

    3.数组引用:

    格式:Type::new

    1. @Test
    2. public void test7() {
    3. Function<Integer, String[]> function = (x) -> new String[x];
    4. String[] strings = function.apply(10);
    5. System.out.println(strings.length);
    6. Function<Integer, String[]> function1 = String[]::new;
    7. String[] strings1 = function1.apply(20);
    8. System.out.println(strings1.length);
    9. }