Java8 方法引用和构造器引用

来源:互联网 发布:淘宝宝贝违规被删除 编辑:程序博客网 时间:2024/06/08 15:21

一、方法引用:有时候你想传递的方法已经有了实现的方法时,就可以使用方法引用,我们可以可以将方法引用理解为 Lambda 表达式的另外一种表现形式.

  1. 对象的引用 :: 实例方法名
PrintStream ps = System.out;Consumer<String> con = (str) -> ps.println(str);con.accept("Hello World!");Consumer<String> con2 = ps::println;con2.accept("Hello World!");
  1. 类名 :: 静态方法名
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);System.out.println(com.compare(1,2));Comparator<Integer> com2 = Integer::compare;System.out.println(com2.compare(1,2));
  1. 类名 :: 实例方法名
BiPredicate<String, String> bp = (x, y) -> x.equals(y);System.out.println(bp.test("abc", "abc"));BiPredicate<String, String> bp2 = String::equals;System.out.println(bp2.test("abc", "abc"));

注意:
①方法引用所引用的方法的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致!
②若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: ClassName::MethodName
二、构造器引用 :构造器的参数列表,需要与函数式接口中参数列表保持一致!
类名 :: new

Supplier<Employee> sup = () -> new Employee();System.out.println(sup.get());Supplier<Employee> sup2 = Employee::new;System.out.println(sup2.get());//多个构造函数时Function<String, Employee> fun = Employee::new;BiFunction<String, Integer, Employee> fun2 = Employee::new;

三、数组引用
类型[] :: new;

Function<Integer, String[]> fun = (args) -> new String[args];String[] strs = fun.apply(10);System.out.println(strs.length);System.out.println("--------------------------");Function<Integer, Employee[]> fun2 = Employee[] :: new;Employee[] emps = fun2.apply(20);System.out.println(emps.length);
原创粉丝点击