lets say I have
public class Student {
public Integer getGrade() { return 1;}
}
and I want to pass this function as Function in java in other class(not Student)
which syntax will allow me doing so?
Function<Student,Integer> = ***
Just do:
Function<Student,Integer> f = Student::getGrade;
You seem to have forgotten to put a name for the variable declaration!
Explanation:
Function<Student,Integer>
represents a function that takes a Student
as parameter and returns an Integer
. Obviously, getGrade
does not satisfy those criteria. But, since calling getGrade
requires a Student
object (because it's an instance method), the compiler can smartly use the Student
parameter passed in to call getGrade
.
If you don't understand what I mean, the syntax is equivalent to:
Function<Student,Integer> f = student -> student.getGrade();
Therefore, the below two lines are the same:
f(myStudent);
myStudent.getGrade();
Function<Student, Integer>
means "you take a student and return any Integer
value":
Function<Student, Integer> f1 = student -> 2;
If you need a student grade, then return this value from the getGrade
method:
Function<Student, Integer> f2 = student -> student.getGrade();
With the method reference, it might be written in a shorter form:
Function<Student, Integer> f3 = Student::getGrade;
Being that getGrade
isn't a static method, you'll need to first instantiate Student
in order to store a reference to it.
Student student = ...;
Supplier<Integer> = student::getGrade;
You'll likely want to use a Supplier
to store reference to the method because your method takes no input and returns one output (whereas a java Function
takes one input and returns one output).
Something like this -
Function<Student, Integer> function = student -> student.getGrade();
or a method reference as
Function<Student, Integer> function = Student::getGrade;