Java8 方法引用

方法引用

方法引用可以被看作仅仅调用特定方法的Lambda的一种快捷写法。如果一个Lambda代表的只是“直接调用这个方法”,那最好还是用名称来调用它,而不是去描述如何调用它。

当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用

构建方式

  1. 类 :: 静态方法

    Comparator<Integer> com2 = Integer::compare;
    System.out.println(com2.compare(12,3));
  2. 类 :: 非静态方法:你在引用一个对象的方法,譬如String::length,而这个对象是Lambda表达式的一个参数。举个例子,Lambda表达式(String s) -> s.toUppeCase()可以重写成String::toUpperCase

    Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2);
    System.out.println(com1.compare("abc","abd"));
    System.out.println("*******************");
    Comparator<String> com2 = String :: compareTo;
    System.out.println(com2.compare("abd","abm"));
  3. 对象 :: 非静态方法

    PrintStream ps = System.out;
    Consumer<String> con2 = ps::println;

构造函数引用

对于一个现有构造函数,你可以利用它的名称和关键字new来创建它的一个引用:ClassName::new。它的功能与指向静态方法的引用类似。

  1. Supplier中的T get()

    Supplier<Employee> sup = () -> new Employee();
    System.out.println("*******************");

    Supplier<Employee>  sup1 = () -> new Employee();
    System.out.println(sup1.get());

    System.out.println("*******************");

    Supplier<Employee>  sup2 = Employee :: new;
    System.out.println(sup2.get());
  2. Function中的R apply(T t)

    Function<Integer,Employee> func1 = id -> new Employee(id);
    Employee employee = func1.apply(1001);
    System.out.println(employee);

    System.out.println("*******************");

    Function<Integer,Employee> func2 = Employee :: new;
    Employee employee1 = func2.apply(1002);
    System.out.println(employee1);
  3. BiFunction中的R apply(T t,U u)

    BiFunction<Integer,String,Employee> func1 = (id,name) -> new Employee(id,name);
    System.out.println(func1.apply(1001,"Tom"));

    System.out.println("*******************");

    BiFunction<Integer,String,Employee> func2 = Employee :: new;
    System.out.println(func2.apply(1002,"Tom"));
  4. 数组引用

    Function<Integer,String[]> func1 = length -> new String[length];
    String[] arr1 = func1.apply(5);
    System.out.println(Arrays.toString(arr1));

    System.out.println("*******************");

    Function<Integer,String[]> func2 = String[] :: new;
    String[] arr2 = func2.apply(10);
    System.out.println(Arrays.toString(arr2));
posted @ 2020-09-02 21:33  GGuoLiang  阅读(169)  评论(0编辑  收藏  举报