这是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)
?
通过将lambda /方法引用声明为参数,它应该变得很明显:
Function<Student, String> getNameFunction = student -> student.getName();
Function<Student, String> getNameMethodReference = Student::getName;
[Student
是Function
的参数,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);