方法引用

117 阅读1分钟

方法引用

什么是方法引用

把已经存在的方法拿过来用 当作函数式接口中抽象方法的方法体 条件

:: 是什么符号

方法引用符

注意事项

需要右函数时接口 被引用方法必须已经存在 被引用方法的形参和返回值需要跟抽象方法保持一致 被引用方法的功能要满足当前的需求

代码演示

public class FunctionDemo1 {
    public static void main(String[] args) {
        Integer[] arr = {3,5,4,1,6,2};
        // 匿名内部类
        Arrays.sort(arr, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        // lambda 表达式
        Arrays.sort(arr,(Integer o1, Integer o2)-> {
            return o2-o1;
        });
         // lambda 简化表达式
         Arrays.sort(arr,(o1, o2)-> o2-o1);
         // 方法引用
        Arrays.sort(arr,FunctionDemo1::substraction);
        System.out.println(Arrays.toString(arr));
    }
    public static int substraction(int num1,int num2){
        return num2-num1;
    }
}

分类

引用静态方法

格式 类名::静态方法

Integer::parseInt

引用成员方法

格式:对象::成员方法

引用其他类的成员方法

格式:其他类对象:: 方法名

引用本类的成员方法

格式:this::方法名

引用父类的成员方法

格式:super::方法名

引用构造方法

格式:类名:: new

范例 Student::new

public static void main(String[] args) {
    // 创建集合
    ArrayList<String> list = new ArrayList<>();
    // 使用工具类 批量添加数据
    Collections.addAll(list,"张无忌,15", "周芷若,14", "赵敏,13", "张强,20", "张三丰,100", "张翠山,40", "张良,35", "王二麻子,37", "谢广坤,41");
    // 需要创建Student类 
    List<Student> newList = list.stream().map(Student::new).collect(Collectors.toList());
    // 结果输出
    System.out.println(newList);

}