37

We have lambda expression for getter as below:

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

How about lambda expression for the setter?

0

2 Answers 2

72

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Can you explain why this works? I thought a 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.
@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.
alternative: Consumer<String> theStudentNameSetter = theStudent::setName; (assuming Student theStudent)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.