34

We have lambda expression for getter as below:

Function<Student, String> studentNameGetter = Student::getName;

How about lambda expression for the setter?

Kowser
  • 8,123
  • 7
  • 40
  • 63

1 Answers1

65

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;
Keppil
  • 45,603
  • 8
  • 97
  • 119
  • 3
    Can you explain why this works? I thought a `BiConsumer` can only be assigned to something like `(Student a, String b) -> a.setName(b)`. But the signature of `setName` has only one parameter. – T3rm1 Aug 18 '17 at 15:15
  • 1
    @T3rm1 it works because `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. – Mukund Jalan Oct 11 '17 at 10:28