Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java <Optional> Object is null or object's property is null?

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?

like image 882
ttolkkiguy Avatar asked Sep 22 '26 22:09

ttolkkiguy


1 Answers

Use Optional.ofNullable and Optional.flatMap

public Optional<String> getUserSex(Person person)
{
    return Optional.ofNullable(person).flatMap(
        p -> Optional.ofNullable(p.getSex())
    );
}
like image 85
Michael Avatar answered Sep 24 '26 11:09

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!