1
public Message setMsg() {
    Message message = null;
    if (send != null || receive != null) {
        message = new Message();
        if (receive != null) {
            message.setReceive(receive);
        }
        if (send != null) {
            message.setSend(send);
        }
    }
    return message;
}

How can I use Optionals in this case instead of this nested if statement?

3
  • Use final Message and if - else if - else to get clean and comprehensible code. Commented Feb 26, 2020 at 23:32
  • The most straightforward way here would be making a stream of 2 receive and send, map them to Optionals of their kind, and reduce them to an optional message. Commented Feb 26, 2020 at 23:49
  • Regard the previous comment as a don't :) Strive to make the listed snippet simpler, forget about rewriting it with Optional. Some points: the method name (does it return or set?), the return type (is set* supposed to return), the last return (always null), too many checks (do you need the first one?), do you need to check before setting (what is being stored in an empty message, nulls? so why check?) Commented Feb 26, 2020 at 23:59

1 Answer 1

2

Not clear what you're trying to achieve but if send and receive were Optional objects you could do something like this:

public Message setMsg() {
    if (!send.isPresent() && !receive.isPresent()) {
        return null;
    }

    Message message = new Message();
    send.ifPresent(message::setSend);
    receive.ifPresent(message::setReceive);
    return message;
}
Sign up to request clarification or add additional context in comments.

2 Comments

If they are not optional, they can be made optional using Optional.ofNullable(send). Upvoted.
Tnx! This is very useful!

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.