方法引用

方法引用是一种更简洁的 Lambda 表达式,可以通过方法名称来引用已存在的方法。方法引用通过 :: 操作符将方法和对象或类名分隔开来表示。

静态方法引用

interface Filter {
    boolean call(Student student);
}

class Student {
    private String name;
    private int age;
    private String gender;
    // 省略 getter 和 setter 方法
}

class Sample {
    public static void main(String[] args) {
        List<Student> students = List.of(
                new Student("张三", 10, "男"),
                new Student("李四", 20, "男"),
                new Student("王五", 30, "女")
        );
        // 过滤出成年的学生
        List<Student> filterPersons = Sample.filter(students, Sample::adult);

        students.stream()
                .filter(Sample::adult)      // 等价于 student -> student.getAge() >= 18
                .forEach(Sample::print);    // 等价于 student -> System.out.println(student);
    }

    static List<Student> filter(List<Student> students, Filter filter) {
        List<Student> result = new ArrayList<>();
        for (Student student : students) {
            if (filter.call(student)) {
                result.add(student);
            }
        }
        return result;
    }

    static Boolean adult(Student student) {
        return student.getAge() >= 18;
    }

    static void print(Student student) {
        System.out.println(student);
    }
}

非静态方法引用

interface Filter {
    boolean call(Student student);
}

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
class Student {
    private String name;
    private int age;
    private String gender;
    // 省略 getter 和 setter 方法

    public boolean isMale() {
        return this.gender.equals("男");
    }
}

class Sample {
    class Util {
        Boolean adult(Student student) {
            return student.getAge() >= 18;
        }

        void print(Student student) {
            System.out.println(student);
        }
    }

    public static void main(String[] args) {
        List<Student> students = List.of(
                new Student("张三", 10, "男"),
                new Student("李四", 20, "男"),
                new Student("王五", 30, "女")
        );
        List<Student> filterPersons = Sample.filter(students, Student::isMale);

        students.stream()
                .filter(Student::isMale)      // 等价于 student -> student.isMale()
                .forEach(System.out::println);    // 等价于 student -> System.out.println(student);
    }

    static List<Student> filter(List<Student> students, Filter filter) {
        List<Student> result = new ArrayList<>();
        for (Student student : students) {
            if (filter.call(student)) {
                result.add(student);
            }
        }
        return result;
    }
}

最后更新于

这有帮助吗?