We have lambda expression for getter as below:
Function<Student, String> studentNameGetter = Student::getName;
How about lambda expression for the setter?
I'm not sure what you mean by creating a lambda expression for the setter.
What it looks like you are trying to do is to assign the method reference to a suitable Functional Interface. In that case, the best match is to a BiConsumer:
BiConsumer<Student, String> studentNameSetter = Student::setName;
BiConsumer<Student, String> can only be assigned to something like (Student a, String b) -> a.setName(b). But the signature of setName has only one parameter.Student a is one parameter & setName has one parameter. So the consumer takes the target object as well as the setter parameter as its parameters.Consumer<String> theStudentNameSetter = theStudent::setName; (assuming Student theStudent)Just to include a concrete example where something like this could be useful:
public static <T extends Serializable> void ifNotNull(Consumer<T> setter, Supplier<T> supplier) {
if (supplier != null && supplier.get() != null) {
setter.accept(supplier.get());
}
}
public static void main(String[] args) {
Model a = new Model();
a.setName("foo");
Model b = new Model();
b.setName("bar");
ifNotNull(b::setName, a::getName);
}
The ifNotNull method receives a setter and a getter but only calls the setter if the result of the getter isn't null.