java—在本例中,如果没有new(),对示例方法的方法引用是如何工作的?

x33g5p2x  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(333)

在collectors.groupingby(student::getgrade,…);使用getgrade()方法时没有新的。getgrade不是静态方法。如果没有新的

class TestClass {
    public static void main(String[] args) {

        var ls = Arrays.asList(new Student("S1", Student.Grade.A),
                new Student("S2", Student.Grade.A),
                new Student("S3", Student.Grade.B),
                new Student("S4", Student.Grade.C),
                new Student("S5", Student.Grade.F));

        var group = ls.stream().filter(student -> student.getGrade() != Student.Grade.F).collect(
                Collectors.groupingBy(Student::getGrade, Collectors.mapping(Student::getName, Collectors.toList())));
        System.out.println(group);

    }
}

lamda格式

var group1 = ls.stream().filter(student -> student.getGrade() != Student.Grade.F).collect(
            Collectors.groupingBy(student -> student.getGrade(), Collectors.mapping(student -> student.getName(), Collectors.toList())));

在学生课堂上,getgrade方法不是静态方法。

class Student {
    public static enum Grade {
        A, B, C, D, F
    }

    private String name;
    private Grade grade;

    public Student(String name, Grade grade) {
        this.name = name;
        this.grade = grade;
    }

    public String toString() {
        return name + ":" + grade;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Grade getGrade() {
        return grade;
    }

    public void setGrade(Grade grade) {
        this.grade = grade;
    }
}
jslywgbw

jslywgbw1#

方法引用匹配 Function<Student, Grade> . 当编译器查看方法时 Student::getGrade ,它看到该方法接受零参数,所以它使用 Student 对象传递给 apply 作为隐式第一个参数(这将适用于抽象方法与引用方法完全匹配的任何函数接口,除非它接受目标类型的附加第一个参数。)在lambda形式中,它如下所示:

(element) -> element.getGrade()

相关问题