Reputation: 8261
We have lambda expression for getter as below:
Function<Student, String> studentNameGetter = Student::getName;
How about lambda expression for the setter?
Upvotes: 37
Views: 28118
Reputation: 1306
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.
Upvotes: 0
Reputation: 46209
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;
Upvotes: 72