lambda的方法引用

方法引用主要有三类:

指向静态方法的引用 如:

 

指向任意类型实例的方法 如:(String s )-> s.toUppeCase()这个对象本身就是lambda的一个参数 写作String::toUpperCase

 

指向先有对象的实例方法的方法引用  指的是在lambda中调用一个已经存在的外部对象中的方法 

如下示例,这里引用的是字符串数组中任意一个对象的compareToIgnoreCase方法。

String[] stringArray = { "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase);

 

构造函数方法的引用

是不将构造函数实例化却能够引用它。

使用它的名称和关键字new来创建它的一个引用

Class::new      它适合Supplier接口的签名 。 ()-> Apple  

Supplier<Apple> c1 = Apple::new;// 利用默认构造函数创建Apple的lambda表达式 等价于 Supplier<Apple> c1 = () -> new Apple();
c1.get();产生一个新的Apple

public void Test2() {
        Function<String, Student> function1 = (name) -> new Student(name); //使用Lambda表达式
        Function<String, Student> function2 = Student::new;                   //使用构造器引用
        System.out.println(function1.apply("Moti"));
        System.out.println(function2.apply("Moti"));
        BiFunction<String, Integer, Student> function3 = (name,age) -> new Student(name, age);//使用Lambda表达式
        BiFunction<String, Integer, Student> function4 = Student::new;                          //使用构造器引用    
        System.out.println(function3.apply("Moti",20));
        System.out.println(function4.apply("Moti",20));    
    }
@Test
    public void Test1() {
        Supplier<Student> supplier = () -> new Student();    //使用Lambda表达式
        Supplier<Student> supplier1 = Student::new;            //使用构造器引用
    }
以上方法中function1和function2对应的构造器是
public Student(String name) {
  this.name = name;
 }
而function3和function4对应的构造器是
public Student(String name, int age) {
      this.name = name;
      this.age = age;
 }
 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值