方法引用

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

主要三种语法格式

对象::实例方法名

注意:需要函数式接口方法的入参和返回值 == 引用的对象方法的入参和返回值

  1. @Test
  2. public void test1(){
  3. Consumer<String> consumer1 = s -> System.out.println(s);
  4. // 优化 对象::实例方法名
  5. // 1:这个是多写了一行,防止直接看不懂,下面才是简化的
  6. PrintStream out = System.out;
  7. Consumer<String> consumer2 =out::println;
  8. // 简化
  9. Consumer<String> consumer3 = System.out::println;
  10. consumer1.accept("hello world");
  11. consumer2.accept("hello world");
  12. consumer3.accept("hello world");
  13. }

image.png

新建类

  1. package com.dance.java8.entity;
  2. import lombok.Data;
  3. @Data
  4. public class Person {
  5. private String name;
  6. private Integer age;
  7. }
@Test
public void test3(){
    Person person = new Person();
    person.setName("flower");
    Supplier<String> supplier = person::getName;
    System.out.println(supplier.get());
}

image.png

类::静态方法名

注意:需要函数式接口方法的入参和返回值 == 引用的对象方法的入参和返回值

@Test
public void test2(){
    Comparator<Integer> comparator = Integer::compare;
}

类::实例方法名

注意:需要两个参数,左边参数作为调用者,右边参数作为入参,才可以使用类::实例方法名

@Test
public void test4(){
    BiPredicate<String,String> biPredicate1 = (x,y) -> x.equals(y);
    // 优化 类::实例方法名
    BiPredicate<String,String> biPredicate2 = String::equals;
}

构造器引用

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

@Test
public void test5(){
    Supplier<Person> supplier1 = () -> new Person();
    // 构造器引用优化
    Supplier<Person> supplier2 = Person::new;
}