Whe*_*hen -5 java java-8 java-stream
This is the student class definition.
public class Student {
public Student(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
}
Run Code Online (Sandbox Code Playgroud)
The map function should accept like a Function interface
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
Run Code Online (Sandbox Code Playgroud)
That means the parameters should be like that
int func(int a){
return b;
}
Run Code Online (Sandbox Code Playgroud)
We need to make sure have one method parameter.
So why getName() can work?
The method actually change to getName(Student this)?
By declaring the lambda/method reference as parameter, it should become obvious:
Function<Student, String> getNameFunction = student -> student.getName();
Function<Student, String> getNameMethodReference = Student::getName;
Run Code Online (Sandbox Code Playgroud)
Student is the parameter to the Function and String is the returned type.
Hence, it matches the map() declaration:
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
Run Code Online (Sandbox Code Playgroud)
And can be used like this:
Stream.of(new Student("")).map(Student::getName);
Run Code Online (Sandbox Code Playgroud)
or without method reference:
Stream.of(new Student("")).map(student -> student.getName());
Run Code Online (Sandbox Code Playgroud)
Or you can even use the declared Function variables:
Stream.of(new Student("")).map(getNameFunction);
Stream.of(new Student("")).map(getNameMethodReference);
Run Code Online (Sandbox Code Playgroud)