Java8新特性 -- Lambda 方法引用和构造器引用

一、 方法引用

若Lambda体中的内容有方法已经实现了,我们可以使用“方法引用”

要求 方法的参数和返回值类型 和 函数式接口中的参数类型和返回值类型保持一致。

主要有三种语法格式:

  • 对象 :: 实例方法名
Consumer<String> consumer1 = System.out::print; //通过 方法引用 实现Lambda体。
consumer1.accept("Hello World!");
  • 类 :: 静态方法名
Comparator<Integer> comparator1 = Integer::compare;  等价于
Comparator<Integer> comparator2 = (x, y) -> Integer.compare(x,y);
  • 类 :: 实例方法名
    Lambda表达式参数列表中的第一个参数是实例方法的调用者,而第二个参数是实例方法的参数时,可以使用 类名 :: 方法名
BiPredicate<String, String> biPredicate = (x,y) -> x.equals(y);
BiPredicate<String,String> biPredicate1 = String :: equals;   

二、构造器引用 

构造器中的参数类型和函数式接口中的参数类型一致。

Supplier<Date> supplier = Date :: new;
Date date = supplier.get();
long time = date.getTime();

三、数组引用

Function<Integer, String[]> function =  String[]::new;
String[] apply = function.apply(10);
System.out.println(apply.length); // 10

猜你喜欢

转载自blog.csdn.net/tb9125256/article/details/81161371
今日推荐