jkd8方法引用

1、什么是方法引用

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

类型语法对应的Lambda表达式
静态方法引用类名::staticMethod(args)->类名.staticMethod(args)
实例方法引用inst::instMethod(args)->inst.instMethod(args)
对象方法引用类名::instMethod(inst,args)->类名.instMethod(args)
构造方法引用类名::new(args)->new 类名(args)

2、示例

Student

@Accessors(chain = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student{
    private String name;
    private int age;
    private int score;
}

ComparatorStudent

public class ComparatorStudent{
    static int comparatorStudent(Student stu1,Student stu2){
        return stu1.getScore()-stu2.getScore();
    }
}

静态方法引用

public class MethodQuote {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        Student s1 = new Student("张三", 18, 92);
        Student s2 = new Student("李四", 19, 86);
        Student s3 = new Student("王二", 17, 77);
        Student s4 = new Student("麻子", 18, 59);

        //原始lambda表达式
        students.sort((x,y)->ComparatorStudent.comparatorStudent(x,y));
        //方法引用调用
        students.sort(ComparatorStudent::comparatorStudent);
        
        //遍历打印
        for (Student student : students) {
            System.out.println(student);
        }
        //stream流方法打印
        students.stream().forEach(System.out::println);

    }
}

实例方法引用

--------缓慢更新中

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值