对于Java8新特性——方法引用的小白理解

什么是方法引用

方法引用是用来直接访问类或者实例的已经存在的方法或者构造方法。方法引用提供了一种引用而不执行方法的方式,它需要由兼容的函数式接口构成的目标类型上下文。计算时,方法引用会创建函数式接口的一个实例。

当Lambda表达式中只是执行一个方法调用时,不用Lambda表达式,直接通过方法引用的形式可读性更高一些。方法引用是一种更简洁易懂的Lambda表达式。
注意方法引用是一个Lambda表达式,其中方法引用的操作符是双冒号"::"。

方法引用
public void test() {

    Consumer<Integer> con = (x) -> System.out.println(x);
    con.accept(100);

    // 方法引用-对象::实例方法
    Consumer<Integer> con2 = System.out::println;
    con2.accept(200);

    // 方法引用-类名::静态方法名
    BiFunction<Integer, Integer, Integer> biFun = (x, y) -> Integer.compare(x, y);
    BiFunction<Integer, Integer, Integer> biFun2 = Integer::compare;
    Integer result = biFun2.apply(100, 200);

    // 方法引用-类名::实例方法名
    BiFunction<String, String, Boolean> fun1 = (str1, str2) -> str1.equals(str2);
    BiFunction<String, String, Boolean> fun2 = String::equals;
    Boolean result2 = fun2.apply("hello", "world");
    System.out.println(result2);
}

构造器引用
public void test2() {

    // 构造方法引用  类名::new
    Supplier<Employee> sup = () -> new Employee();
    System.out.println(sup.get());
    Supplier<Employee> sup2 = Employee::new;
    System.out.println(sup2.get());

    // 构造方法引用 类名::new (带一个参数)
    Function<Integer, Employee> fun = (x) -> new Employee(x);
    Function<Integer, Employee> fun2 = Employee::new;
    System.out.println(fun2.apply(100));

}

数组引用

public void test(){
// 数组引用
Function<Integer, String[]> fun = (x) -> new String[x];
Function<Integer, String[]> fun2 = String[]::new;
String[] strArray = fun2.apply(10);
Arrays.stream(strArray).forEach(System.out::println);
}

总结:
方法引用使得开发者可以直接引用现存的方法、Java类的构造方法或者实例对象。方法引用和Lambda表达式配合使用,使得java类的构造方法看起来紧凑而简洁,没有很多复杂的模板代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值