3

I would like to migrate this legacy Java example code to Java 8.

public String getUserSex(Person person) {
    if(person != null) {
        if(person.getSex() != null) {
            return person.getSex();
        }
    }

    return null;
}  

How to migrate this to Java 8 using Optional?

1
  • What exactly is your question? Commented Oct 16, 2017 at 12:37

2 Answers 2

8

Use Optional.ofNullable and Optional.flatMap

public Optional<String> getUserSex(Person person)
{
    return Optional.ofNullable(person).flatMap(
        p -> Optional.ofNullable(p.getSex())
    );
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could implement it as follows:

public Optional<String> getUserSex(Person person) {
    if(person != null) {
       return Optional.ofNullable(person.getSex());
    }
    return Option.empty();
} 

In that case the caller of getUserSex will always get an typed Optional an therefore the caller must not implement null checks.

Instead the caller can ask the Optional if the value is present.

 getUserSex(new Person()).isPresent()

1 Comment

You should use Optional.ofNullable() because the getSex method can return null like the given code shows.

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.