为什么stream()。map()可以接受map(Student :: getName)之类的参数

问题描述 投票:-5回答:1

这是student类定义。

public class Student {
    public Student(String name) {
        this.name = name;
    }
    private String name;

    public String getName() {
        return name;
    }

}

map功能应像Function接口一样接受

<R> Stream<R> map(Function<? super T, ? extends R> mapper);

这意味着参数应该像这样

int func(int a){
    return b;
}

我们需要确保有一个方法参数。那么为什么getName()可以工作?方法实际上更改为getName(Student this)

java java-8 java-stream
1个回答
5
投票

通过将lambda /方法引用声明为参数,它应该变得很明显:

Function<Student, String> getNameFunction = student -> student.getName();
Function<Student, String> getNameMethodReference = Student::getName;

[StudentFunction的参数,String是返回的类型。

因此,它与map()声明匹配:

<R> Stream<R> map(Function<? super T, ? extends R> mapper);

并且可以这样使用:

Stream.of(new Student("")).map(Student::getName);

或没有方法参考:

Stream.of(new Student("")).map(student -> student.getName());

或者您甚至可以使用声明的Function变量:

Stream.of(new Student("")).map(getNameFunction);
Stream.of(new Student("")).map(getNameMethodReference);
© www.soinside.com 2019 - 2024. All rights reserved.